Create function that checks isset and returns null if not

98 Views Asked by At

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?

2

There are 2 best solutions below

1
hakki On

You can use property_exists build-in function.

property_exists — Checks if the object or class has a property

https://www.php.net/manual/en/function.property-exists.php

so

property_exists($row, 'color')

Note:

As opposed with isset(), property_exists() returns true even if the property has the value null.

0
Rain On

You can use the Null coalescing operator

$items[] = [
  'color' => $row->color ?? null
];