Reputation: 13884
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
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.
Upvotes: 2