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 (an integer or string) of the element currently pointed to. If the pointer points past the end of the elements list or the array is empty, it returns null.

πŸ› οΈ 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() returns null.
  • 3. Foreach Loops: In standard foreach loops, key() is rarely needed since foreach ($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(), and prev().
  • It returns null when the internal pointer points to an invalid or out-of-bounds element.