19

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.

1
  • $result = implode('', array_map(fn($el) => "<li>$el</li>", array_filter($item))); Commented Dec 16, 2022 at 23:35

16 Answers 16

38

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;
}

Note that unlike original empty(), this mempty() function will emit a Warning level error message if you try to use it with undefined variable or a non-existent array index. Hence it cannot be considered a 100% substitution.

Sign up to request clarification or add additional context in comments.

10 Comments

This should be the best answer. A succinct helper function I can reuse in multiple places.
Does this not still trigger errors if a variable is undefined, though?
Yes, see my Update at the bottom of the answer; if you pass an undefined variable or non-existent array index, it will display an error.
See: sandbox.onlinephpfunctions.com/code/… and click execute and you will see an error
@fdrv you would call it like this: $var3 = mempty($var1, $var2);. If either $var1 or $var 2 has a non-empty value it will return false, otherwise true.
|
24

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)) {

1 Comment

i consider this a much better answer than the accepted answer… the accepted answer works… BUT only as long as the function exists at runtime… this answer uses built-in PHP functions and therefore more reliable and transportable
9

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.

Comments

8

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.

Comments

3

I use this function as an alternative to isset. It's a little simpler than @imkingdavid's one and return true, if all arguments (variables) are not empty, or return false after first empty value.

function isNotEmpty() {
    foreach (func_get_args() as $val) {
        if (empty($val)) {
            return false;
        }
    }

    return true;
}

1 Comment

var_dump(empty($nonexistsnt)); var_dump(isNotEmpty($nonexistsnt));
3

Just adding to the post by imkingdavid;

To return TRUE if any of the parameters are empty, check out the below instead.

function mempty(...$arguments)
{
    foreach($arguments as $argument) {
        if(empty($argument)) {
            return true;
        }
    }
    return false;
}

This is closer to how isset() works, and is how i would expect empty() to work if supporting a variable length of parameters. This will also keep in line with how empty() works in that it will return FALSE if everything is not empty.


If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

PHP: isset - Manual

1 Comment

Darn. I didn't see this post by hovado. My apologies.
2

Save yourself some typing and put it into a loop...

foreach (array('vFoo','vSomeValue','vAnother') as $varname) {
  if (!empty($$varname)) $result .= '<li>'.$$varname.'</li>';
}

3 Comments

Isn't that simply wrong code? Wouldn't you do foreach (array(...) AS $var) and skip at least one of the variable variables? And anyway, I don't think this 'in' syntax exists in PHP.
+1 Absolutely right. (What was I thinking? Javascript? Ugh.) Fixed it! I'm confident about the variable variables, though.
there is till a problem in this coe.....you need to remove the extra $ in the $varname
1

As others noted, empty() takes only one argument so you have to use something like

if(!empty($v1) && !(empty($v2) ...)

but if (!empty($v)) is the same thing as if($v) so you may also use:

if ($v1 && $v2 ...)

6 Comments

if (!empty($v)) is not the same thing as if ($v). $v generates an error if $v is undefined, whereas empty($v) returns true if $v is undefined or evaluates to (boolean) false.
@awn: it is according to the manual, except that one does not generate a warning.
You're right... warning, not error. Still, warnings mess up my page layout.
@awm: It's not even a warning. It's a notice; semantically a debug message. It indeed depends on the context if syntactic salt for notice suppression is necessary.
It's not even a warning, and it still messes up my page layout? Darn that error_reporting(E_ALL).
|
1

Why not just loop through the $item array

foreach($item as $v) {
    if(!empty($v))) {
        $result .= "<li>$v</li>";
    }
}

You could also validate of the key index value as well

foreach($item as $key => $value) {
    if($key == 'vFoo') {
        if(!empty($value))) {
            $result .= "<li>$value</li>";
        }
    }
    // would add other keys to check here
}

For the empty() versus isset()

$zero = array(0, "0");

foreach($zero as $z) {
    echo "\nempty(): $z ";
    var_dump($z);
    var_dump(empty($z)); // Will return true as in it's empty
    echo "isset(): $z ";
    var_dump(isset($z)); // will return true as it has value
}

Output:

empty(): 0 int(0)
bool(true)
isset(): 0 bool(true)

empty(): 0 string(1) "0"
bool(true)
isset(): 0 bool(true)

19 Comments

What's the point of isset($v) here? We already know $v is set because it's the parameter of the foreach loop.
Pendantic note, the isset call is redundent here, since there is no case where !empty($v) will be true where isset($v) will be false. So that simplifies to !empty($v). Now, if it wasn't in a loop, you should put the isset() call first since the variable may not be set. But in the code you provided, just get rid of it all together...
I like to use the isset() as well to check for 0 values but I had it as && instead of ||.
@Phill: Hi Phill, I'm not sure I can pass them to one array as each variable has it's own name + value i.e. <li><strong>$Foo</strong>: $ValueofFoo</li>
@Nathan: I would have to print them only if they have a value, but if either of them is empty the others still need to be printed.
|
0

Why not just like this:

foreach(array_filter($input_array) as $key => $value) {
    // do something with $key and $value
}

1 Comment

because array_filter() will reduce the array to an array only with entries that are not empty… therefore creating an array that will result in a false "not empty"…
0

Just for the record: array_reduce works as well.

if (!array_reduce($item, function($prev_result,$next) {
    return $prev_result || empty($next); // $prev_result will be initial null=false
})) {
    // do your stuff
}

Comments

0

Unfortunately, almost every answer here is wrong, because almost everyone didn't bother to learn the actual behavior of PHP's empty() language construct.

In reality, it's impossible to replicate this command's behavior for multiple values. Because, unlike empty(), a userland function will always emit a Warning in case a tested variable doesn't exist.

Although for variables it can be circumvented with passing arbuments by reference, something like this,

function mempty(&...$args)
{
    foreach ($args as $var) {
        if (empty($var)) {
            return true;
        }
    }
    return false;
} 

this function has a limitation of its own as it will only accept variables, while original empty() can accept any expression.

At the same time, as long as all variables are deliberately set, one simply don't need empty() at all, and can use variables themselves:

if($vFoo && $vSomeValue && $vAnother) {
    // do something only if all three have thruthy values
}

However, using empty() (of casting to bool) is considered a bad practice nowadays. It tests for too many different values. And in the modern PHP code such tests should be explicit. For example, for strings it must be like

if(strlen($vFoo) && strlen($vSomeValue) && strlen($vAnother)) {
    // do something only if all variables contain non-empty strings
}

Comments

-1

I'm not 100% sure I understand what you're trying to do, but here are a couple of possible answers:

This will return each variable only if it isn't empty:

function printIfNotEmpty($var) {
  if (!empty($var)) {
    return '<li>' . $var . '</var>';
  }
  return '';
}
$result .= printIfNotEmpty($vFoo);
$result .= printIfNotEmpty($vSomeValue);
$result .= printIfNotEmpty($vAnother);

Or this one will add all three of them if none of them are empty:

if (!empty($vFoo) && !empty($vSomeValue) && !empty($vAnother)) {
  $result .= '<li>' . $vFoo . '</li>';
  $result .= '<li>' . $vSomeValue . '</li>';
  $result .= '<li>' . $vAnother . '</li>';
}

1 Comment

shouldn't it be written like this if (!empty($vFoo && $vSomeValue && $vAnother) )?
-1

Guys, many thanks for all your responses, I kind of created a script based on all of our possible answers which is actually helping me with learning PHP's syntax which is the cause behind most of my errors :) So here it is

$vNArray ['Brandon']  = $item[3]; 
$vNArray['Smith']= $item[4]; 
$vNArray ['Johnson']= $item[5];
$vNArray ['Murphy']= $item[6];
$vNArray ['Lepsky']= $item[7];

foreach ($vNArray as $key => $value){

    if(!empty($value)){
        $result  .= "\t\t\t\t<li><strong>$key</strong>"  .$value.   "</li>\n";
}

I just need to figure out how to make some of these different now. So could I access each in the following way?

$result  .= "\t\t\t\t<li><strong>$key[0]</strong>"  .$value. "</li>\n";
$result  .= "\t\t\t\t<li><a href="thislink.com">$key[3]</a>"  .$value. "</li>\n";

Thanks guys!

Comments

-1

If working only with strings, you may try the following:

if(empty($str1.$str2.$str3)){ /* ... */ }

Note, that empty(0) would return true, while empty('0'.'0') and empty('0') won't.

6 Comments

I should had mentioned that this will not work that way the op asked because the equal function will return true if all strings are empty in this case. You can not use this method to validate if all strings are NOT empty, only if not all are empty: !empty($str1.$str2)is equal to !empty($str1) or !empty($str2) wich is not the same as !empty($str1) and !empty($str2).
But it's an easy and short hand way to proove if all strings are empty.
why only with string?
Well, back then variables in php were not typed (not saying they are today, but it's possible now to somewhat enforce types). Also, how should the concept of emptyness be translated to other types i.e. numbers or boolenas?
variables can contain null, 0 or false values. they are all treated as empty
|
-1

You can try php &&/ and operator. They both are same.

if(!empty($vFoo) && !empty($vSomeValue) && !empty($vAnother) {
   $result .= "<li>$vFoo</li>"
   $result .= "<li>$vSomeValue</li>"
   $result .= "<li>$vAnother</li>"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.