note 58355 deleted from language.types.boolean by colder

From: Date: Tue, 17 Oct 2006 18:47:43 +0000
Subject: note 58355 deleted from language.types.boolean by colder
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-118657@lists.php.net to get a copy of this message
Note Submitter: johnjc-phpdoc at publicinfo dot net ---- The === and !== are not fully documented in either the Comparison Operator or Booleans type sections. They are talked about a bit more in the sections on strpos() and array_search() but they refer you to the section on Booleans for further information. I am putting my contribution on === and !== in the Booleans section with pointers to it from the comment areas of other sections. This refers only to the use of === and !== with functions like strpos() and array_search() which may a needle at character 0 in a string or element 0 in an array. Because the 0 returned by the function evaluates to == 'false' === and !== are used. You can say <?php if ( strpos($needle,$haystack) !== false ) { print "found it\n"; } ?> and you can say <?php if ( strpos($needle,$haystack) === false ) { print "didn't find it\n"; } ?> but you cannot say <?php if ( strpos($needle,$haystack) === true ) { print "found it \n"; } ?> nor can you say <?php if ( strpos($needle,$haystack) !== true ) { print "didn't find it\n"; } ?> This is because strpos() and array_search do not return 'true' when successful and the numbers they return do not evaluate to === true. So you cannot use 'true' in any way with these functions. I frequently find myself adding string elements to an array as I find them and using the growing array as my record of what has already been done such as <?php if ( array_search($needle,$haystack) !== false ) { print "done one of those already\n"; } ?> or <?php if ( array_search($needle,$haystack) === false ) { print "got a new one\n"; array_push($haystack,$needle) } ?> The more natural way to say this would have been the other way around: <?php if ( array_search($needle,$haystack) === true ) { print "done one of those already\n"; } ?> or <?php if ( array_search($needle,$haystack) !== true ) { print "got a new one\n"; array_push($haystack,$needle) } ?> because you don't go around saying, "if this is not false", you say "if this is true". But that won't work. Now I've had it explained to me it makes sense that the function doesn't return 'true' because it returns a number value instead. And given that === checks the type you can't have the number evaluate to '=== true'. But the result for the user of PHP is counter-intuitive and so deserves specific documenting.

« previous php.notes (#118657) next »