Earlier today I tried to do this:
Example 1:
<?php
echo $myVar || "rawr";
?>
I thought this might print out $myVar if it was set, and print "rawr" if not.
It printed a 1, I assume this is the result of the OR test.
What I then tried was this:
Example 2:
<?php
if ($myVar)
{
echo $myVar;
}
else
{
echo "rawr";
}
?>
Which is what I was trying to accomplish.
I think I understand why the first prints the results of the OR test rather than one of the variables, and also why I tried it – been spending some time on the bash shell recently 🙂
Can anyone tell me if there is a way to perform the text in example #2 but in similar syntax to example #1?
PHP is notoriously inelegant in this department, and there really is no good way of making this test.
As a general solution, you ‘d need to use the ternary operator as in
empty($var) ? "rawr" : $var. However, in practice what happens is that you have one of two scenarios:1. Your own variable
In this case where you define the variable yourself, the best solution is to just give it a known default value at the place you define it (possibly with the ternary operator).
2. Inside an array
If the array is one that should not be touched like one of the superglobals, then you can wrap the test inside a function (pretty much that’s what everyone does).
If the array is one under your jurisdiction but it comes from an external source, you can use the “add the defaults” trick:
At this point you know for a fact that every key inside
$defaultsalso exists inside$incoming.