Tuesday 23 September 2014

PHP: more boolean / null confusion (and perhaps not entirely on my part)

G'day:
I'm so very confused.


What do you make of this code?

<?php
// false.php

$testResultString = "isset: as string: [%s]; as binary: [%b]; null: [%b]; type: [%s]; null equiv: [%b]<br>";

$does = true;
$set = isset($does);
echo sprintf($testResultString, $set , $set, is_null($set), gettype($set), $set == null);

$set = isset($doesNot);
echo sprintf($testResultString, $set , $set, is_null($set), gettype($set), $set == null);

This outputs:

isset: as string: [1]; as binary: [1]; null: [0]; type: [boolean]; null equiv: [0]
isset: as string: []; as binary: [0]; null: [0]; type: [boolean]; null equiv: [1]


Observations:

  • isset() returns 1 for true and (possibly) null for false. It was this that was pissing me off on the weekend and stimulated me to write "PHP: a fractal of [etc]... yeah, I'm now getting where you're coming from". This would be like a CFML function returning "Yes" for true and 0 for false. Surely if there was any concern for detail, it'd be true/false or 1/0 (or 0/-1 etc)? It's one thing - as Sean reminded me - for null to be interpreted as false, but for it to actually be used as a false value seems a bit incoherent to me.
  • But the value returned is not null, if it's checked for nullness.
  • If it's checked for type, it's a boolean
  • And if it's compared to null, it is null
Huh?

--
Adam