RemiDG RemiDG - 6 months ago 23
PHP Question

Short if this else that in PHP?

I was searching for some shorthand if/else code, but unlike

$var ? $a : $b
it doesn't need an 'else'-like returned value. What I want would be basically this, but shorter:

$myVariable = "abc";
echo $myVariable ? $myVariable : "hello";
echo $myVariable ? "hello" : $myVariable;


I'm kind of used to do such a thing in Lua, which goes like:

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 wondered, does PHP have the functionality to do such a thing?
Thanks.

Answer
$myVariable ? $myVariable : ""; 

is equivalent to:

$myVariable ?: "";

PS: You should be aware that PHP does type juggling here. This is basically the same as:

if ($myVariable == TRUE) ...

If $myVariable happens to be a string like 0, it will evaluate to false. However 00 will evaluate to true. I've found this not so useful as it appears to be. In many cases you will need to check if $myVariable is set first, or do a type comparison and make sure the variable is boolean...