Reputation: 63
$a = '';
$b = 1;
How to print $b if $a = '' using shorthand in PHP?
in javascript there is something like
a || b;
Upvotes: 2
Views: 6567
Reputation: 950
As others ahve said Turnary operator is handy for most senarios.
echo $a ?: $b;//b
But it is NOT shorthand for empty(). Ternary operator will issue notices if var/array keys/properties are not set.
echo $someArray['key that doesnt exist'] ?: $b;//Notice: Undefined index
echo $arrayThatDoesntExist['key-that-doesnt-exist'] ?: $b;//Notice: Undefined variable
empty() will take care of the additional checks for you and its recomended to just use it.
if (empty($arrayThatDoesntExist['key-that-doesnt-exist'])) echo $b;
You could technically just suppress the warning/notice with @ and the ternary operator becomes a replacement for empty().
@echo $someArray['key that doesnt exist'] ?: $b;
@echo $arrayThatDoesntExist['key-that-doesnt-exist'] ?: $b;
But usually not recommended as supressing notices and warnings could lead you into trouble later on plus I think it may have some performance impact.
Upvotes: 1
Reputation: 961
This is the shorthand for an IF/Else
statement in PHP.
echo ($a != '' ? $a : $b)
If $a
is not an empty string output (echo) $a
otherwise output $b.
Upvotes: 1
Reputation: 36964
$a = '';
$b = 1;
echo $a ?: $b; // 1
Until $a is evaluated false, $b will be displayed. Remember that the following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
That means that if $a is "", 0, "0", null, false, array(), .. then $b will be displayed. See PHP type comparison tables.
If you want to display $b only when $a is an empty string, then you should uses strict comparison operators (===)
$a = '';
$b = 1;
echo $a === '' ? $b : ''; // 1
Upvotes: 8