-3

I need to make a conditional statement where the 5 variables should be empty before perform an action. The problem is some variables can be zero, false or NULL value. How to catch all of them?

Which one is better?

If (!$a && !$b && !$c && !$d && !$e) {

  // do some action 

} else {

  exit;

}

OR

If (empty($a) && empty($b) && empty($c) && empty($d) && empty($e)) {

  // do some action 

} else {

  exit;

}

Thank you.

Drunken M
  • 2,013
  • 2
  • 11
  • 18
  • 2
    You should first define to yourself exactly what 'empty' means. – castis Jul 23 '18 at 16:38
  • 3
    Using `empty` means you won't get any errors if the variables don't exist, but otherwise these are equivalent. Use whichever makes you feel warm and fuzzy inside. – iainn Jul 23 '18 at 16:42

2 Answers2

1

First of all, use "code sample" to show code.

When you use !$a you are actually casting $a to boolean. The problem here is

$a = 0;
if (!$a) {
  echo 'NOT EMPTY';
} else {
   echo 'EMPTY';
}
//OUTPUT EMPTY BECAUSE 0 to boolean is FALSE

Same example with NULL value.

About empty i advice you to check the documentation

Read it and choose the way that fit your needs.

Hope this helps

0

This could be an approach to check multiple variables are empty at once.

<?php
$a = $b = $c = $d = $e = '';
#$b = 5; // comment out to go on else block
if (empty($a . $b . $c . $d . $e)){
    echo "All variables are empty, do what you want to do man";
}else{
    echo "One of variable is not empty";
}
?>
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103