1
\$\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
Your Common Sense
9,1231 gold badge22 silver badges51 bronze badges
asked Sep 1, 2022 at 12:20
\$\endgroup\$
1
  • \$\begingroup\$ CodeReview Search: [php] elvis \$\endgroup\$ Commented Sep 2, 2022 at 11:12

1 Answer 1

2
\$\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') ?: []);
answered Sep 1, 2022 at 14:06
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.