0

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.

Lovelock
  • 7,689
  • 19
  • 86
  • 186
  • 2
    any variable used in an expression is evaluate to be falsy or truthy. falsy means empty, null, equal to 0, or to false. truthy is anything else. so, testing !$var tests for all kind of values you would consider as false. – njzk2 Jan 24 '14 at 18:55

3 Answers3

3

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.

Martin Samson
  • 3,970
  • 21
  • 25
2

$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.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Pieter
  • 1,823
  • 1
  • 12
  • 16
1

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337