Reputation: 8085
just doing some validation and wanted to learn really what this meant instead of it just working.
Lets say i have:
$email = $_POST['email'];
if(!$email) {
echo 'email empty'
}
Whats is just having the variable and no check for it = something mean?
I thought
$variable
by its self meant that it returned that variable as true.
So i am also using if
!$variable
is means false.
Just wanted to clear up the actual meaning behind just using the variable itself.
Is it also bad practice to compare the variable for being empty?
So is it better to use
$email == ''
Than
!$email
Sorry if its a small question without a real answer to be solved, just like to 100% understand how what i am coding actually works.
Upvotes: 0
Views: 77
Reputation: 1833
$email = ''
will empty the variable. You can use ==
or ===
instead.
In this case, it's better to use PHP's isset()
function (documentation). The function is testing whether a variable is set and not NULL
.
Upvotes: 2
Reputation: 227270
When you do if(<expression>)
, it evaluates <expression>
, then converts it to a boolean.
In the docs, it says:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
So, when you do if(!$email)
, it converts $email
to a boolean following the above rules, then inverts that boolean.
Upvotes: 1
Reputation: 4090
PHP evaluates if $email
is "truthy" using the rules defined at http://www.php.net/manual/en/language.types.boolean.php.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
PS $email= ''
will assign ''
to $email
.
Upvotes: 3