Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check multiple conditions in multidimensional array

I want to check fruit name in array and check if color value is 1. Its showing error Cannot use object of type stdClass as array

if(checkFruits('apple','red')){
   //ok 
}
function checkFruits($fruit = null, $color = null) {
 $fruits = Array ( [0] => stdClass Object ( [id] => 1 [fruit] => apple [red] => 1 [yellow] => 0 [1] => stdClass Object ( [id] => 2 [fruit] => orange [red] => 0 [yellow] => 1 ) );
 foreach($fruits as $val){
     if($val['fruit'] == $fruit && $val[$color] == 1){
          return true;
     }
  }
 return false;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are looping over the $fruit parameter, a scalar variable instead of the $fruits array.

Also you code to create an array would not work I changed that also

function checkFruits($fruit = null, $color = null) {
    $fruits = (object) [
                    (object) ['id' =>1, 'fruit' => 'apple', 'red' => 1, 'yellow' => 0],
                    (object) ['id' =>1, 'fruit' => 'orange', 'red' => 0, 'yellow' => 1]
        ];

    foreach($fruits as $val){
        if($val->fruit == $fruit && $val->{$color} == 1){
             return true;
        }
     }
    return false;
}

if (checkFruits('apple', 'red')) {ECHO 'YES Apples are red';}

RESULT

YES Apples are red
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading