I'm working with ACF in WP which provides a get_field()
function. The function can return an array of values, null
or false. When the result of the function doesn't contain an array of values I want to default to an empty array.
This is how I do it at the moment but would like to know if there's a neater way to accomplish the same thing.
// can these lines be combined into one without multiple function calls?
$field = get_field('mobile_menu', 'option');
$field = $field ? $field : [];
return collect($field); // other processing
1 Answer 1
Shake Rattle and Roll ?:
The ternary short cut ?:
, A.K.A. "the Elvis operator" has been available since PHP 5.3.
Elvis face superimposed with characters
It could be used to simplify that second line:
$field = $field ? $field : [];
to:
$field = $field ?: [];
That could be used on the line where get_field()
is called:
$field = get_field('mobile_menu', 'option') ?: [];
which would allow for the elimination of the second line.
At that point $field
is a single-use variable and can be eliminated:
return collect(get_field('mobile_menu', 'option') ?: []);
[php] elvis
\$\endgroup\$