Knowing if a value exists in an array

Asked

Viewed 18 times

2

I have the following array in 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 a certain 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 tried using if (array_search('regulacao', $menu)) but he returns false

Any hint?

  • You should consider both the value in principal as in submenu?

  • @Andersoncarloswoss yes

  • One day: to ask, prefer to put the result of var_export, because it’s easier to copy the array that is testing and still readable.

1 answer

1

I solved with the function below:

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;
} 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.