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. Why does this produce this error. What is it about isset() function that does not throw this error when $row->color is passed to it -- when the same argument passed to my custom function does throw the error?
My Answer:
'red',
'size' => 'small'
];
function getProperty($items, $property) {
if (isset($items[$property])) {
return $items[$property];
} else {
return null;
}
}
echo getProperty($items, 'color'); // Output: red
echo getProperty($items, 'size'); // Output: small
echo getProperty($items, 'weight'); // Output: null
Rate this post
3 of 5 based on 1826 votesComments