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".

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP key() to Retrieve Keys from Associative Arrays

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 />
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPTutorialkey functionassociative array
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.