Victor Marchuk
Victor Marchuk

Reputation: 13884

In PHP return result or empty array

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?

Upvotes: 1

Views: 53

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

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

Upvotes: 2

Related Questions