-2

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?

WillD
  • 5,170
  • 6
  • 27
  • 56
  • 3
    Why don't you just use the [`null coalescing operator`](https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op)? – DarkBee Aug 18 '22 at 14:34
  • I love the suggestion of the null coalescing operator and will use that. However, can anyone explain the difference between isset() and checkEmpty() in how they handle the argument passed to them? What magic is it play that allows meto pass a failing value to isset with no error but not to my checkEmpty()? – WillD Sep 08 '22 at 13:52

2 Answers2

1

You can use the Null coalescing operator

$items[] = [
  'color' => $row->color ?? null
];
Rain
  • 3,416
  • 3
  • 24
  • 40
-1

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.

hakki
  • 6,181
  • 6
  • 62
  • 106
  • You need to pass the object as the first argument and peoperty name as the second argument `property_exists($row, 'color')` – Rain Aug 18 '22 at 14:46