0

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;
}
limio
  • 25
  • 4
  • Your `$fruits = .....` line of code is not PHP code – RiggsFolly Apr 05 '22 at 10:07
  • perhaps `get_object_vars` would be of use within your logic or `$val->{$color}`? – Professor Abronsius Apr 05 '22 at 10:07
  • Maybe the problem is with that initialization? `$fruits = [ ['fruit' => 'apple', 'red' => 1, 'yellow' => 0], ['fruit' => 'apple', 'red' => 1, 'yellow' => 0]];` – Diego D Apr 05 '22 at 10:09
  • @RiggsFolly this is the output of `print_r($fruits)` – limio Apr 05 '22 at 10:09
  • So do your `foreach` over the `$fruits` array and not the parameter `$fruit` – RiggsFolly Apr 05 '22 at 10:15
  • @RiggsFolly ohh yes, Sorry for the mistake – limio Apr 05 '22 at 10:18
  • 2
    _"this is the output of print_r($fruits)"_ - but that does not make for valid, executable code - so just throwing it in there among the rest of the code, makes really little sense, in terms of providing a _proper_ minimal reproducible example of your issue. Hint: `var_export` exists. – CBroe Apr 05 '22 at 10:20

2 Answers2

0

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
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

You can use associative array

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