PHP
π PHP key() Function: Fetching the Current Array Key
The key() function in PHP returns the key of the element currently pointed to by an array's internal pointer. It provides read-only information without advancing or modifying the array pointer.
-
Return Value:
key()returns the key (anintegerorstring) of the element currently pointed to. If the pointer points past the end of the elements list or the array is empty, it returnsnull.
π οΈ Basic Usage with Indexed Arrays
By default, when an array is initialized, its internal pointer sits at the very first element:
PHP
$fruits = ["Apple", "Pear", "Banana"];
// Fetch current key (default pointer is at index 0)
echo key($fruits);
/*
Output:
0
*/
π Pointer Movements: Combining with next() & reset()
When functions like next(), prev(), or reset() alter the position of the internal array pointer, key() reflects the updated index location immediately:
PHP
$fruits = ["Apple", "Pear", "Banana"];
// Move the internal pointer to the next element ("Pear")
next($fruits);
echo key($fruits); // Outputs: 1
// Move pointer to the next element ("Banana")
next($fruits);
echo key($fruits); // Outputs: 2
π§© Usage with Associative Arrays
key() works identically on associative arrays, returning the string key of the active pointer location:
PHP
$user = [
"a" => "Apple",
"b" => "Pear",
"c" => "Banana"
];
echo key($user); // Outputs: a
π Key Rules & Behaviors
-
1. Read-Only Operation:
key()only reads position data; it never moves the internal pointer or mutates the array. -
2. Invalid Pointers: If the array pointer moves beyond the array limits (e.g. after traversing past the last item with
next()),key()returnsnull. -
3. Foreach Loops: In standard
foreachloops,key()is rarely needed sinceforeach ($arr as $k => $v)already provides key access safely.
π Quick Feature Summary
| Feature | Description |
|---|---|
| Primary Function | Returns the key of the current array element |
| Modifies Array? | β No (Pure inspection) |
| Uses Internal Pointer? | β Yes |
| Return Type | int | string | null |
-
π Short Summary
-
key()inspects the active array pointer and extracts its key name or numeric index. -
It is ideal for manual array pointer navigation alongside
current(),next(), andprev(). -
It returns
nullwhen the internal pointer points to an invalid or out-of-bounds element.
