php - what does ($variable) return?
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.
Answer
Solution:
PHP evaluates if
$email
is "truthy" using the rules defined at http://www.php.net/manual/en/language.types.boolean.php.PS
$email= ''
will assign''
to$email
.Answer
Solution:
$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 notNULL
.Answer
Solution:
When you do
if(<expression>)
, it evaluates<expression>
, then converts it to a boolean.In the docs, it says:
So, when you do
if(!$email)
, it converts$email
to a boolean following the above rules, then inverts that boolean.