phparraysphp-5.5

PHP Array Search Return Multiple Keys


I'm trying to search an array and return multiple keys

<?php
$a=array("a"=>"1","b"=>"2","c"=>"2");
echo array_search("2",$a);
?>

With the code above it only returns b, how can I get I to return b and c?


Solution

  • As it says in the manual for array_search:

    To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.


    Example:

    $a=array("a"=>"1","b"=>"2","c"=>"2");
    print_r(array_keys($a, "2"));
    

    Result:

    Array
    (
        [0] => b
        [1] => c
    )