check whether a string exists in an array that is inside another array

Asked

Viewed 603 times

1

I have the following variable with name $array which has the following values

array (size=5)
  0 => 
    array (size=1)
      'name' => string 'a' (length=7)
  1 => 
    array (size=1)
      'name' => string 'b' (length=7)
  2 => 
    array (size=1)
      'name' => string 'c' (length=3)
  3 => 
    array (size=1)
      'name' => string 'd' (length=5)
  4 => 
    array (size=1)
      'name' => string 'f' (length=6)

and I have the variable named $check that is with the value 'a'.

I want to check if the variable’s value $check exists in the array of the variable $array

I’ve tried with the in_array, but I can only access by setting the key number this way:

if(in_array($check, $array[0])):
    echo "existe";
    else:
    echo "nao existe";
endif;
  • 1

    Please use the site snippet only for HTML/CSS/JS codes that are complete and playable. For PHP, use the {} editor. Also more attention to the tags used, your question has no relation to HTML. Finally, try to write correctly, including accents; the more correct you write, the easier communication will be.

1 answer

1


Just you go through your array and call the function in_array for each value:

function has_value($neddle, $arr)
{
    foreach ($arr as $value) {
        if (in_array($neddle, $value) {
            return true;
        }
    }

    return false;
}

Now, if the amount of "array array" levels varies, you will need to do this implementation recursively.

Browser other questions tagged

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