The key
method is used to get the key of the element pointed by the internal pointer of the array.
In PHP, each array contains an internal pointer that points to the current element. It initially points to the first element of the array. We can move the pointer positions using methods like
next
,prev
, etc.
key(array|object $array): int|string|null
If an array is empty, or if the internal pointer points to an invalid position (like beyond the array length), then null
is returned.
<?php$numbers = ['one' => 1,'two' => 2,'three' => 3,'four' => 4];echo "Current key is : ". key($numbers). "\n";echo "Moving internal pointer forward 2 position \n";next($numbers);next($numbers);echo "Current key is : ". key($numbers). "\n";?>
In the code above:
We created a numbers
array.
We printed the key of the current element pointed by the internal pointer, using the key
method.
We used the next
method two times to move the pointer position forward two positions.
We again printed the current key pointed by the internal pointer of the array, using the key
method.