0
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ CodeReview Search: [php] elvis \$\endgroup\$ Commented Sep 2, 2022 at 11:12

1 Answer 1

1
\$\begingroup\$

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') ?: []);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.