-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)==''){
}
4
  • !empty is what you want. This checks if something is NOT empty. Commented Mar 26, 2019 at 17:33
  • 1
    Here is an ideea, concatenate the variables: if(empty($var1 . $var2))... Commented Mar 26, 2019 at 17:34
  • Not much shorter:if(array_filter([$a, $b])) Commented Mar 26, 2019 at 17:34
  • The shortest way isn't always the best way - but you're probably better off using arrays than separate variables if you can. Commented Mar 26, 2019 at 17:37

3 Answers 3

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

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

4 Comments

Interesting, you can concat variables in an IF statement?
Of course you can, @Adam. :-)
Today I learned, awesome!
empty()considers [] as empty. This approach won't work if one of the variable is an empty array [].
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)

1 Comment

Alternatively you can use the splat operator instead of func_get_args()
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!

2 Comments

Aaaaaand I think I misread that. Swear it said "how do I check that they both aren't empty". Welp! My bad =]
I suppose you could also try array_merge: if ( !empty(array_merge($var1, $var2)) ) { // code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.