Using if(!empty) with multiple variables not in an array

HGB picture HGB · Feb 14, 2011 · Viewed 91.8k times · Source

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.

Answer

imkingdavid picture imkingdavid · Oct 17, 2011

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.