While playing with strings one should be VERY VERY VERY cautious when trying to check for a “null” value
PHP has the bad habit of considering empty strings to be “null” and “false” , for instance
1 2 3 4 | $foo = ''; if( $foo == null && $foo == false ){ echo "So PHP actually considers empty strings to be null and false"; } |
To avoid this either use
1 2 3 | is_null( $foo ) //or $foo === null |
Try this code
1 2 3 4 5 6 7 8 9 10 11 12 | $foo = ''; if( $foo == null && $foo == false){ echo 'So PHP actually considers empty strings to be null AND false!'; } if( !is_null( $foo )){ echo 'Using is_null() will return true only if $foo is null'; } if( $foo !== null ){ echo 'Using === and !== also works well'; } |
so, $foo = ” doesn’t make $foo null!
right?
Strictly speaking
$foo = ” is an empty (String)
$foo = null is nothing , not a number not a object , just nothing
In most ,if not all, programming languages null is not equal to an empty string or integer who’s value is zero.
PHP on the other appears to allow this
consider this example
function getPhoneNumberFromDatabase(){
if( $db->getConnection() == false ){
return null;
}
return $db->getPhoneNumber();
}
in many cases you will want your functions to return NULL upon failure
so if we do this
$phone = getPhoneNumberFromDatabase();
if( $phone == null ){
echo ‘Database connection failed’;
}
In this case , PHP will report that “Database connection failed” even if the connection is okay but the phone number was an empty string.
That’s why you should use is_null or === null