phparraysfilter

Get the key of the last qualifying value in an array


I need to have an array_search search my array strictly making sure that the item is identical (meaning the whole thing is the same thing as the input value). I know about the third variable in a array_search() function in PHP - the Strict one, but I don't want it to check if its the same instance, as it is not. How would I do this?

Here is the code I'm currently using:

array_search(some, array(someItem,anothervariable, yetanothervariable, some)); 
//output - 0 (the first item) which contains some but isn't exactly some.

Requested output:

Instead of outputting the first item that contains some, someItem, it would output the key for the last item, 3, that is the exact search value.


Solution

  • Are you open to using a foreach loop instead of array_search?

    If so try this:

    $haystack = array('something', 'someone', 'somewhere', 'some');
    $needle = 'some';
    
    foreach($haystack as $key=>$straw){
        if($straw === $needle){
            $straws[$key] = $straw;
            }
        }
    
    print_r($straws);
    

    it will print

    Array ( [3] => some ) 
    

    Or you could use array_keys() with the search value specified.

    Then, using the same $haystack and $needle above:

    $result = array_keys($haystack,$needle,TRUE);
    print_r($result);
    

    This returns:

    Array ( [0] => 3 ) 
    

    The first argument is the array to return keys from, The second arg is the search value, if you include this arg, then only keys from array elements that match the search value are returned. Including the third boolean arg tells the function to use match type as well (===).