How to use PHP in_array with associative array?

前端 未结 6 1682
夕颜
夕颜 2020-12-03 00:15

Is there any php function such as in_array for associative arrays you get by the mysql function \"mysql_fetch assoc\" ?

For example, if I have an $array that looks l

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 00:47

    First you must know which part of the associative array you're going to use as haystack in in_array function. Then you can use in_array without additional code.

    Example with values :

     "apple", 2 => "banana", 3 => "lemon", 4 => "pear");
    $haystack = array_values($assoc);
    echo "

    " . print_r($assoc, true) . "

    "; $needle = 'banana'; $find = (in_array($needle, $haystack)) ? 'TRUE' : 'FALSE'; echo "

    $needle : $find

    "; $needle = 'cherry'; $find = (in_array($needle, $haystack)) ? 'TRUE' : 'FALSE'; echo "

    $needle : $find

    "; ?>

    Results in :

    Array ( [1] => apple [2] => banana [3] => lemon [4] => pear )
    
    banana : TRUE
    
    cherry : FALSE
    

提交回复
热议问题