Jump to content

Trying to understand bools and string representations


AFTNHombre

Recommended Posts

I have this inequality which should produce a boolean but it appears to produce a nothing. I'm expecting a result that is either TRUE or FALSE but it appears to be an empty string or something. At least, that's what it appears to do when I try to get its string representation:

$not_null = ($group_map != NULL);
Log::Trace("group map is not null: '$not_null'");

$group_map is an array, FWIW. I was trying to find out what it was, because the code was behaving unpredictably. I thought that when I just tested it for NULL I should get something I could understand, but even that went weird on me. What is $not_null if not a boolean?

Oh, and the trace message comes out as:

group map is not null: ''

Php's loose (==,  !=) comparison operator table indicates that an empty array is == to null (true). Therefore, a != comparison would be false.

 

Your $not_null will either be a TRUE or a FALSE (the result of the comparison.) When you echo a FALSE value, nothing is displayed (echoing a TRUE does display a 1.)

 

Use var_dump($not_null); to see exactly what you are getting.

 

What exactly are you trying to test? Using empty($group_map) might be clearer. If $group_map doesn't exist or is an empty array, empty() will return TRUE.

 

 

Ah, well now we have another layer of complication.

$group_map != NULL ? 'TRUE' : 'FALSE'

yields different results from

$group_map !== NULL ? 'TRUE' : 'FALSE'

var_export() indicates that $group_map is an empty array. I'm tracing down a bug here, and shortly after my debug code there's an if statement that tests the results of the non-identical inequality, so now I have to wonder if the original developers were aware that

$group_map != NULL

would trigger FALSE for an empty array.

Using a strict comparison (===, !==), the only thing that null is exactly equal to === is another null and anything else (true,false,number,string, empty string, array, empty array,...) compared with a null is false. A !== between two null values would be false and anything else compared !== with a null is true.

Empty and NULL are 2 distinctly different concepts. An empty array isn't NULL, it's simply an empty array. Using a loose comparison when testing for a NULL or boolean value is the wrong way to go about it. You should always use a strict comparison against a NULL or boolean value.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.