Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...