key

Returns the key at the array's current internal pointer position, without moving the pointer.

Signature
key(array|object $array): int|string|null
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$arrayarray|objectThe array to read the current key from. Not modified — the pointer is not advanced.

Return value

int|string|nullThe key of the element the internal pointer is on, or null if the pointer is past the end of the array or the array is empty.

Errors

Does not throw. Emits a deprecation notice since PHP 8.1.0 when called on an object.

Changelog

  • PHP 8.1.0Calling this function on objects is deprecated. Convert the object with get_mangled_object_vars() first, or use a class implementing Iterator such as ArrayIterator.
  • PHP 7.4.0Instances of SPL classes are now treated like empty objects with no properties instead of calling the Iterator method of the same name.

key is the companion to current: where current gives you the value at the internal pointer, key gives you its key. Neither moves the pointer.

When to reach for it

Its most valuable role is as the end-of-array test for manual traversal. Because it returns null only when the pointer has run past the last element, while (key($array) !== null) is the loop condition that survives falsy values — unlike testing current, which stops on a stored false, 0 or ''.

It is also the way to report the key alongside a value found by pointer-based scanning, for instance echoing the name of each matching entry as you step through with next.

What trips people up

People forget that null is a legitimate value in arrays but never a legitimate key — PHP casts a null key to the empty string ''. That is exactly why key can use null as an unambiguous "past the end" signal, and why === null is a safe test.

The pointer is shared state on the array. Any sort function resets it, copying the array copies its position, and passing the array to a function that calls next on a reference will move it under you. In new code, foreach ($array as $key => $value) or array_key_first normally expresses the intent better.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Terminate a manual next()/current() loop correctly even when values can be false or zero.
  • Report which key a pointer-driven scan is currently sitting on.
  • Read the first key of an array after reset() without iterating.

Frequently asked questions

What is the difference between key and array_key_first?

key returns the key at the internal pointer, which may be anywhere, while array_key_first always returns the first key regardless of pointer state. Use array_key_first when you want the first key and do not care about the cursor.

Why does key() return null?

The internal pointer has moved past the last element, or the array is empty. Since null can never be an actual array key, this is an unambiguous end-of-array signal.

Does key() move the array pointer?

No. Like current, it only reads the current position; use next, prev, reset or end to move the pointer.

More examples

The correct pointer loop

All three rows print, including pear => 0, because the loop tests the key rather than the value. Writing while ($v = current($stock)) would have stopped at pear and silently dropped plum.

Example · php
<?php
$stock = ['apple' => 5, 'pear' => 0, 'plum' => 12];
reset($stock);

while (($k = key($stock)) !== null) {
    echo $k, ' => ', current($stock), "\n";
    next($stock);
}

Finding the key of a match while scanning

The scan prints f1 and f3, the keys of both apples, which in_array could not give you and array_search would only give for the first. array_keys($fruits, 'apple') is the modern one-liner for the same result.

Example · php
<?php
$fruits = ['f1' => 'apple', 'f2' => 'orange', 'f3' => 'apple'];
reset($fruits);

while (key($fruits) !== null) {
    if (current($fruits) === 'apple') { echo key($fruits), "\n"; }
    next($fruits);
}

key without the pointer

key() reflects hidden state that any earlier code could have changed, while array_key_first and array_key_last always answer about the array itself. Prefer the latter pair unless you are deliberately running a cursor.

Example · php
<?php
$conf = ['host' => 'db1', 'port' => 5432];
next($conf);                      // pointer is on 'port'

echo key($conf), "\n";            // port — depends on pointer state
echo array_key_first($conf), "\n"; // host — independent of the pointer
echo array_key_last($conf), "\n";  // port

Discussion

  • Be the first to comment on this lesson.