Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create function that checks isset and returns null if not

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading