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.

+3


source to share


6 answers


$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 ...

+4


source


You don't need to use the ternar else statement, you can always do something like:

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

      



Which prints nothing if not $ myVariable

+2


source


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.

+2


source


As of PHP 5.3, you can:

echo $myVariable ?: "hello";

      

The icon is equal to:

echo $myVariable ? $myVariable : "hello";

      

I think the second option is not possible.

+2


source


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

      

It doesn't get any shorter than the above in PHP. This should check that $ myVariable has a value and print it, otherwise print "hello"

+2


source


Everyone is doing the same. Even shorter in php 7

$var = $var ?? $var;

      

0


source







All Articles