Reputation: 1785
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?
Upvotes: 1
Views: 440
Reputation: 290
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
}
}
Upvotes: 0
Reputation: 4513
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;
}
Upvotes: 2