Using PHP key() to Retrieve Keys from Associative Arrays
This article explains the PHP key() function, its parameters and return values, and demonstrates with a complete example how to iterate over an associative array to output the keys whose values match a specific condition, such as finding all keys for the value "apple".
The key() function returns the key name of the current element in an array without moving the internal pointer. If the pointer is beyond the end of the array or the array is empty, it returns NULL .
Parameter: array – the associative array to operate on.
Return value: The key of the current array element, or NULL if no element is selected.
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) . '<br />';
}
next($array);
}
?>The script iterates through $array , checks each value, and prints the corresponding key when the value equals "apple".
Output:
fruit1<br />
fruit4<br />
fruit5<br />Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.