I'm trying to output a value of on object, but the value might not exist for some object records. How do I return the value without raising error "Undefined property: stdClass"?
For example, I have an object:
$obj = '[{"id":111,"value1":1,"value2":2},{"id":111,"value1":1}]';
value2
does not exist for the second element in the array, and I want to write a function to process each object in the array. Example:
function add($obj){
$sum = 0;
foreach($obj as $o){
$sum += $o->value1;
if(isset($o->value2)){
$sum += $o->value2;
}
}
return $sum;
}
The if
part is what I want to improve. There might be dozens of other values that don't exist for some object. I don't want to write if(isset($o->valueN))
every time.
Is there any other easier ways to code this to avoid the undefined property error?