Let me explain this further, So I tend to do something like:
$foo = "";
$bar = "This is not empty"
if($foo){
$str = $foo;
}else{
$str = $bar;
}
magic($str)
I thought this is a really nasty way to approach this and there got to be some easy syntax to achieve this and i’m just being dumb.
So i tried:
magic($foo OR $bar)
Unfortunately that actually compares the two variables and returns 1 instead of the actual true variable itself.
Basically i want a syntax that checks if the first variable is empty then it’ll return the second one instead.
Yes, in PHP 5.3 or later, use the new version of the ternary operator:
If you need to support PHP 5.2 or earlier you’ll have to use the slightly more verbose
See http://php.net/manual/en/language.operators.comparison.php
Note neither these or your
if($foo){ $str = $foo; } else{ $str = $bar; }check the value of$bar, your question title doesn’t quite match the body.If you have multiple items and you want to remove the empty ones you can use
array_filter, eg:array_filter(array($foo, $bar, $baz));