Lovelock Lovelock - 18 hours ago 3
PHP Question

PHP checking if item exists in array and then return the value - convert to a function

Working on a WordPress site and using Advanced Custom Fields. I am looping through an flexible content array and creating an array from the return.

The issue is I need to return differently named images in an array but the images might be null (they can be empty).

This currently works:

"images" => [
"image_one" => ( $l['image_one']['url'] ? $l['image_one']['url'] : NULL ),
/* etc */
]


But this is in a switch statement so I wanted to be able to pass the:

$l['image_one']['url']


To a function and only return the URL if there is one. However I could have a array where $l['image_three']['url'] is not set and not in the array returned so I will always get undefined offset notices.

I can carry on the way I am but its getting repetive and would rather be able to do e.g.:

"image_one" => imageExists($l['image_one']['url'])


But of course I am already calling a key that doesn't exist (possibly). Is there an other methods of tidying up my shorthand if?

Answer

Use isset() on your ternary condition:

function imageExists($image) {
    return isset($image['url']) ? $image['url'] : NULL;
}

And invoke with:

imageExists($l['image_one']);

If you're on a version >= PHP 7.0, you can use the null coalescing operator (search here.) For:

function imageExists($image) {
    return $image['url'] ?? NULL;
}
Comments