RCWH
RCWH

Reputation: 53

Checking conditions in multidimensional array

I have an array like this:

$_SESSION['food'] = array( 
   array(
      "name" => "apple",
      "shape" => "round",
      "color" => "red"
  ),
   array(
      "name" => "banana",
      "shape" => "long",
      "color" => "yellow"
  )
);

I want to make a statement that checks whether any particular combination of values exists within any of the second level arrays above.

So, basically:

if NAME=APPLE and COLOR=RED in FOOD // returns true
if NAME=BANANA and COLOR=GREEN in FOOD // returns false
if NAME=APPLE and SHAPE=LONG in FOOD // returns false

How would I construct the if() statements above (just one statement as an example would be sufficient)? I am really stumped here.

I suspect it has something to do with running an in_array() within a foreach(), but I am not sure of the exact syntax.

Thanks a lot for any help.

Upvotes: 2

Views: 1178

Answers (3)

Felix Kling
Felix Kling

Reputation: 816394

You have to loop over all the arrays and you could use array_intersect_assoc for comparison:

function contains($haystack, $needle) {
    $needle_length = count($needle);
    foreach($haystack as $sub) {
        if(is_array($sub) 
            && count(array_intersect_assoc($needle, $sub)) === $needle_length) {
            return true;
        }
    }
    return false;
}

and call it with:

$red_apple = array('name'=>'apple','color'=>'red');

if(contains($_SESSION['food'], $red_apple)) {
    // something
}

With this you can easily check for any combination of values for any array containing arrays.

Upvotes: 1

ehudokai
ehudokai

Reputation: 1926

function existsInArray($name, $color){
    foreach($_SESSION['food'] as $foodItem){
         if($foodItem['name'] ==$name && $foodItem['color'] == $color){
              return true;
         }
    }
    return false;
}

hope that helps!

Upvotes: 0

codaddict
codaddict

Reputation: 455000

Something like:

foreach($_SESSION['food'] as $fruit) {
        if($fruit['name'] == 'apple' && $fruit['color'] == 'red') {
                return true;
        }
}

Upvotes: 4

Related Questions