(PHP 4, PHP 5, PHP 7, PHP 8)
key — Fetch a key from an array
key() returns the index element of the current array position.
array
The array.
The key() function simply returns the
key of the array element that's currently being pointed to by the
internal pointer. It does not move the pointer in any way. If the
internal pointer points beyond the end of the elements list or the array is
empty, key() returns null
.
Version | Description |
---|---|
8.1.0 | Calling this function on object s is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator , such as ArrayIterator , instead. |
7.4.0 | Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. |
Example #1 key() example
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array), "\n";
}
next($array);
}
?>
The above example will output:
fruit1 fruit4 fruit5
Note that using key($array) in a foreach loop may have unexpected results.
When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)
I was incorrectly using:
<?php
foreach($array as $value)
{
$mykey = key($array);
}
?>
and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)
CORRECT:
<?php
foreach($array as $key => $value)
{
$mykey = $key;
}
A noob error, but felt it might help someone else out there.
Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this
<?php
$array = array(
'0' => '5',
'1' => '2',
'2' => '0',
'3' => '3',
'4' => '1');
// wrong approach
while ($fruit_name = current($array)) {
echo key($array).'<br />';
next($array);
}
// the way will be break loop when arra('2'=>0) because its value is '0', while(0) will terminate the loop
// correct approach
while ( ($fruit_name = current($array)) !== FALSE ) {
echo key($array).'<br />';
next($array);
}
//this will work properly
?>