PHP Conditional Expression Evaluation With TRUE and FALSE
Conditional expressions (both if and while statements) are literal or boolean or numeric.
Numeric expressions evaluate to true when they are non-zero – zero/0 is false.
String expressions evaluate to TRUE when there is nonempty string. A NULL value is evaluated as
false.
How do you assign a NULL to a string or any other type of variable?
$s_var = NULL; // or just set it to false – that is null too
This little code snippet demonstrates the value of TRUE and FALSE ( 1 and NULL ), with strings and numbers
<?php echo 'We are setting $hungry to true <br>'; $hungry=TRUE; print 'The value of the $hungry variable is: '.$hungry; echo "<br>"; echo $hungry ? "Lets eat now" : "Not hungry yet"; echo '<br>We are setting $hungry to false<br>'; $hungry=FALSE; if ($hungry) { echo "Now food please"; } else { echo "Can we eat later?"; } echo "<br>"; print "The value of the \$hungry variable is $hungry"; print "<br> So what were are saying is TRUE = 1 and FALSE=NULL "; echo "<br> Now lets set the var to NULL and see that it also matches FALSE <br>"; $hungry=NULL; if ($hungry) { echo "Now food please"; } else { echo "Can we eat later?"; } echo "<br>"; echo 'now lets change $hungry\'s data type to number, remembering any numeric value including 0/zero will evaluate to true'; echo "<br>"; $hungry = 0; if ($hungry) { echo "Now food please"; } else { echo "Can we eat later?"; } echo "<br>"; echo "<br>"; echo 'now lets change $hungry\'s data type to string'; echo "<br>"; $hungry = "famished"; if ($hungry) { echo "Now food please"; } else { echo "Can we eat later?"; } ?>We are setting $hungry to true
The value of the $hungry variable is: 1
Lets eat now
We are setting $hungry to false
Can we eat later?
The value of the $hungry variable is
So what were are saying is TRUE = 1 and FALSE=NULL
Now lets set the var to NULL and see that it also matches FALSE
Can we eat later?
now lets change $hungry’s data type to number, remembering any numeric value except 0/zero will evaluate to true
Now food please
now lets change $hungry’s data type to string
Now food please