'Check multiple conditions in multidimensional array [duplicate]
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 1:[1]
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
Solution 2:[2]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
