简体   繁体   中英

Find value on array in PHP

I have an array on variable $menu :

array (size=3)
  0 => 
    array (size=2)
      'principal' => string 'regulacao' (length=9)
      'submenu' => string 'agenda' (length=6)
  1 => 
    array (size=2)
      'principal' => string 'regulacao' (length=9)
      'submenu' => string 'marcacao' (length=8)
  2 => 
    array (size=2)
      'principal' => string 'gestao' (length=6)
      'submenu' => string 'usuarios' (length=8)

I need to know if an word exists, ex:

if (array_value_exists('regulacao')) //return true
if (array_value_exists('marcacao')) //return true
if (array_value_exists('usuarios')) //return true
if (array_value_exists('gestao')) //return true

I trying using if (array_search('regulacao', $menu)) but it's not works

Any idea?

I believe this code solves your problem:

function recursive_array_search($needle, $haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle === $value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return true;
        }
    }
    return false;
} 

Array_search not works with nested array.

To do this search you need to iterate your $menu array and call array_search on each sub array. Like this:

$word = "regulacao";
foreach($menu as $arr) {
    $arrKey = array_search($word, $arr);
    if($arrKey){
        print "Found {$word} in key {$arrKey}";
        // break; <-- uncomment this line for search only one occurrence
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM