PHP检查项目是否存在于数组中然后返回值 - 转换为函数

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?

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;
}

Normally I would just do it inline but since you are looking for a function:

function imageExists($arr = null) {
    return (empty($arr['url'])) ? null : $arr['url'];
}

imageExists($l['image_one']);