lookdad lookdad - 2 months ago 7
PHP Question

How does empty() work with a boolean expression?

A guy learning PHP sent me some code that has me scratching my head. He's getting

$_POST
input, putting it in variables, and then:

if( !empty($id && $name && $email) ) {
//do something
}


My first inclination was that passing multiple variables as an argument would throw an error, but it evaluates successfully. Am I incorrect that
empty()
should NOT take a boolean expression? Or - if I'm right - why does it work?

Answer

You can pass an expression to empty rather than a variable (since PHP 5.5), but with an expression like that you lose half of the benefit of using empty. empty checks that variables are set as well as evaluating their "truthiness". When you give it an expression like that, the individual variables within the expression are not checked to exist by empty. The expression is just evaluated as a boolean.

So if you used separate empty checks, you would get the check that the variables exist as well as the check that they are != false

if(!empty($id) && !empty($name) && !empty($email))

But when you use

if (!empty($id && $name && $email))

You will still get into the if block if all the variables are set and have non-false values, but you'll get undefined variable notices if any of them are not set. It's basically the same thing as not using empty at all, like this:

if ($id && $name && $email)

But if your guy is setting these variables from $_POST, they will be set, (if they weren't in $_POST he'd get undefined index warnings at that point) and the empty here is pointless anyway.

Comments