1

In javascript I can write something like:

var result = Whatever() || [];

and if Whatever() returns null or undefined, the result variable will contain an empty array.

Is there a similar shortcut in PHP? This will just return false:

$result = Whatever() || array();

I can use a ternary operator, but since there is a function call, I will need to create an additional variable like so:

$whatever = Whatever();
$result = $whatever ? $whatever : array();

which seems ugly and not very readable. Is there a better pattern?

1
  • return Whatever() ? Whatever() : []; or return Whatever() ? Whatever() : array() - as you said, those are your best bets - it's called a Ternary Operator or shortcutted : davidwalsh.name/php-shorthand-if-else-ternary-operators Commented Jul 2, 2015 at 8:57

1 Answer 1

2

Stop reading old php posts on internet. You can easily do

$result = Whatever() ?: array();

PHP 5.3+

And nope, Whatever() won't be called twice.

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.