-1

With these variables:

$var1='a';
$var2='b';

How can I check if they are both empty at once without the need of doing this:

if(empty($var1) && empty($var2)){
}

or

if($var1=='' && $var==''){
}

I mean something like:

if(($var1 && $var)==''){
}

3 Answers3

1

Depending on your scale requirements and how large the data you'll be storing in these vars is, you could just do a straight concatenation:

if($var1 . $var2 == '') {
    // blank strings in both
}

Alternatively, using empty():

if(empty($var1 . $var2)) {
    // blank strings in both
}

Repl.it

esqew
  • 42,425
  • 27
  • 92
  • 132
1

How about a utility function:

function is_any_empty() {
    $args = func_get_args();
    foreach($args as $arg) {
        if(empty($arg)) return true;
    }
    return false;
}
var_dump(is_any_empty("")); // bool(true)
var_dump(is_any_empty("ds", "")); // bool(true)
var_dump(is_any_empty("ds", "dd")); // bool(false)
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
0

I mean, that's kinda how you do it. But if you want to ensure that they both are not empty, you'd probably want your if statement to look more like this:

if(!empty($var1) && !empty($var2)) {
  // Do stuff! They both exist!
}

I'd prefer an empty check because if $var1 and $var2 haven't been defined, you'll get notices all over your error logs.

Hope that helps!

Rohjay
  • 101
  • 1
  • 7
  • Aaaaaand I think I misread that. Swear it said "how do I check that they both aren't empty". Welp! My bad =] – Rohjay Mar 26 '19 at 17:38
  • I suppose you could also try array_merge: `if ( !empty(array_merge($var1, $var2)) ) { // code` – Rohjay Apr 05 '20 at 11:45