In short, what if this is something else in PHP?
I was looking for some shorthand if / else code, but unlike $var ? $a : $b
it doesn't need the "else" return value. I want it to be mostly but shorter:
$myVariable = "abc";
echo $myVariable ? $myVariable : "hello";
echo $myVariable ? "hello" : $myVariable;
I'm kind of used to doing this kind of thing in Lua that looks like this:
local myVariable = "abc" -- In case myVariable is false, print "hello". Otherwise it prints "abc" print ( myVariable or "hello" ) -- In case myVariable does have something (So, true) print "goodday." print ( myVariable and "goodday" )
So, I was wondering if PHP has the functionality to do such a thing? Thank.
source to share
$myVariable ? $myVariable : "";
equivalent to:
$myVariable ?: "";
PS: You should be aware that PHP does indeed create juggling here. This is basically the same as:
if ($myVariable == TRUE) ...
If $myVariable
it turns out to be a string like 0
, it will evaluate to false. However, 00
will evaluate to true. I find this is not as useful as it sounds. In many cases, you will need to check if a parameter is set $myVariable
or do a type comparison and make sure the variable is boolean ...
source to share
echo (!empty($myVariable)) ? $myVariable : "hello";
or
echo (isset($myVariable)) ? $myVariable : "hello";
Since PHP is a badly typed language $myVariable
, containing 0
or ""
may be considered false . And you have to check if the variable exists, or at least make sure it is a string.
source to share