I have the following issue. I want to access a property of an object which may or not be there.
Consider this:
$items[] = [
'color' => $row->color
];
But color may or not be set on $row when it’s not PHP prints a notice that it is something like this:
Warning: PHP Notice: Undefined property: stdClass::$color
So I want to do this instead:
$items[] = [
'color' => isset($row->color) ? $row->color : null,
];
However that’s a lot of code to write each time I want to do this. Perhaps I’ll have dozens of similar properties.
So I would like to create a function like:
function checkEmpty($testValue){
if(!isset($atestValue)) {
return $testValue;
} else {
return null;
}
}
and use it
$items[] = [
'color' => checkEmpty($row->color),
];
But this produces the same error as before. I think because I am still trying to access $row->color when I invoke checkEmpty. Is there a way I can create a reusable function to achieve this isset check and return null if not?
>Solution :
You can use the Null coalescing operator
$items[] = [
'color' => $row->color ?? null
];