PHP 8.4.24 Released!

Voting

: one plus five?
(Example: nine)

The Note You're Voting On

helenadeus at gmail dot com
17 years ago
I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack = array('a','b','a','b');

$needle = 'a';

print_r(array_search_all($needle, $haystack));

//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )

function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

    foreach ($haystack as $k=>$v) {
    
        if($haystack[$k]==$needle){
        
           $array[] = $k;
        }
    }
    return ($array);

    
}

?>

<< Back to user notes page

To Top