Using if(!empty) with multiple variables not in an array
I am trying to polish some code with the if(!empty)
function in PHP but I don't know how to apply this to multiple variables when they are not an array (as I had to do previously) so if I have:
$vFoo = $item[1];
$vSomeValue = $item[2];
$vAnother = $item[3];
Then I want to print the result only if there is a value. This works for one variable so you have:
if (!empty($vFoo)) {
$result .= "<li>$vFoo</li>";
}
I tried something along the lines of
if(!empty($vFoo,$vSomeValue,$vAnother) {
$result .= "<li>$vFoo</li>"
$result .= "<li>$vSomeValue</li>"
$result .= "<li>$vAnother</li>"
}
But of course, it doesn't work.
Solution 1:
You could make a new wrapper function that accepts multiple arguments and passes each through empty(). It would work similar to isset(), returning true only if all arguments are empty, and returning false when it reaches the first non-empty argument. Here's what I came up with, and it worked in my tests.
function mempty()
{
foreach(func_get_args() as $arg)
if(empty($arg))
continue;
else
return false;
return true;
}
Side note: The leading "m" in "mempty" stands for "multiple". You can call it whatever you want, but that seemed like the shortest/easiest way to name it. Besides... it's fun to say. :)
Update 10/10/13: I should probably add that unlike empty() or isset(), this mempty() function will cry bloody murder if you pass it an undefined variable or a non-existent array index.
Solution 2:
You need to write a condition chain. Use &&
to test multiple variables, with each its own empty()
test:
if (!empty($vFoo) && !empty($vSomeValue) && !empty($vAnother)) {
But you probably want to split it up into three ifs, so you can apply the extra text individually:
if (!empty($vFoo)) {
$result .= "<li>$vFoo</li>";
}
if (!empty($vSomeValue)) {
$result .= "<li>$vSomeValue</li>";
}
if (!empty($vAnother)) {
Solution 3:
empty()
can only accept one argument. isset()
, on the other hand, can accept multiple; it will return true if and only if all of the arguments are set. However, that only checks if they're set, not if they're empty, so if you need to specifically rule out blank strings then you'll have to do what kelloti suggests.
Solution 4:
use boolean/logical operators:
if (!empty($vFoo) && !empty($vSomeValue) && !empty($vAnother)) {
$result .= "<li>$vFoo</li>"
...
}
Also, you might want to join these with or
instead of and
. As you can see, this can give you quite a bit of flexibility.