[英]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. 在WordPress网站上使用高级自定义字段。 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: 但这是在switch语句中,因此我希望能够传递:
$l['image_one']['url']
To a function and only return the URL if there is one. 对于一个函数,如果有则仅返回URL。 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.
但是我可以有一个数组,其中未设置$ l ['image_three'] ['url']且不在返回的数组中,因此我将始终获得未定义的偏移量通知。
I can carry on the way I am but its getting repetive and would rather be able to do eg: 我可以继续我的方式,但是它会重复,并且宁愿能够做到:
"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?
如果还有其他方法可以整理我的速记?
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']);
Use isset()
on your ternary condition: 在三元条件下使用
isset()
:
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: 如果使用的版本> = PHP 7.0,则可以使用null合并运算符( 在此处搜索。 )
function imageExists($image) {
return $image['url'] ?? NULL;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.