A coder's home for Marc "Foddex" Oude Kotte, who used to be located in Enschede, The Netherlands, but now in Stockholm, Sweden!
PHP Lesson 1: TRUE and FALSE in PHP world
PHP is a truly wonderful language. Type safety is a non existent concept, yet the absence of it also allows you to perform wonderful hacks. In light of this a miniature lesson in PHP: what constitutes TRUE in PHP, and what FALSE? I'll answer this by answering what constitutes FALSE: everything else (and I literally mean
everything else) constitutes TRUE.
So why is this important? Many coders use code constructs like this:
$value = some_function();
if ($value)
do_something_else();
If the
some_function
function returns a value of type
bool
, then there is really no question: if
true
is returned,
do_something_else
will be executed, if
false
is returned it won't. But... what if an array is returned? A floating point value? A string? An empty string? An object? NULL? These values will all in some way be converted to a boolean value:
true
or
false
. The list below indicates what values in PHP are converted to
false
. As said, all other possible values not listed here will convert to
true
.
false
(type bool
)0
(type int
, variations with more zero's as well)0.0
(type float
, variations with more zero's at either side of the dot as well)null
(the constant)""
(an empty string)"0"
(a string containing the digit 0)array()
(an empty array)
To test the above theory, try to execute the following:
<?php
foreach (array( false, 0, 0.0, null, "", "0", array() ) as $value)
if ($value)
echo "Oops, foddie was wrong";
Luckily for me, this will produce no output at all.... (at least in PHP 5 ;-))
1 comment(s)
Click to write your own comment