Search array by values and return keys

10,138

Solution 1

foreach ($array1 as $key => $value) {
    if ($value == 'c' && $array2[$key] == '3') {
        echo "The key you are looking for is $key";
        break;
    }
}

I'm pretty sure there's a saner way to do whatever you're trying to do though.

Solution 2

The function returned exactly as it should have. The first occurrence of value 'c' exists at index 1 in $array1 and the value '3' has its first occurrence at index 0 in $array2

This behavior is documented in the php docs on array_search and it even supplies you with an alternative if you don't like it:

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

Share:
10,138
conmen
Author by

conmen

Updated on June 04, 2022

Comments

  • conmen
    conmen almost 2 years

    I have values passed c and 3 from $_GET variable, which I want to look up in an array as values and retrieve their keys. How can I search through the array to return accurate keys?

    The code below

    <?php
    
    $array1 = array(0 => 'a', 1 => 'c', 2 => 'c');
    $array2 = array(0 => '3', 1 => '2', 2 => '3');
    
    $key1 = array_search('c', $array1);
    $key2 = array_search('3', $array2);
    
    ?>
    

    returns

    $key1 = 1;
    $key2 = 0;
    

    though I am expecting

    $key1 = 2;
    $key2 = 2;