Req #49426 [Opn->Wfx]: Logic error in boolean cast from string
| From: | requinix@php.net | Date: | Mon, 19 Dec 2016 09:26:40 +0000 |
| Subject: | Req #49426 [Opn->Wfx]: Logic error in boolean cast from string | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-206126@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=49426&edit=1
ID: 49426
Updated by: requinix@php.net
Reported by: az at kreatiefer dot de
Summary: Logic error in boolean cast from string
-Status: Open
+Status: Wont fix
Type: Feature/Change Request
Package: Scripting Engine problem
Operating System: *
PHP Version: *
Block user comment: N
Private report: N
New Comment:
After seven years I think we can wontfix this.
@az: String to bool conversion will not take a numeric value into account. It's straight from
string to boolean and only "0" is treated as false. If you don't want two casts then
you can compare to 0, as in $strTestVar != 0.
https://3v4l.org/UepTW
@miklcct: You aren't the only one who feels that way, but the behavior cannot be changed now
because there's just too much code out there relying on "0" being false - sometimes
without even knowing. It's a backwards compatibility problem.
Previous Comments:
------------------------------------------------------------------------
[2016-12-19 09:03:49] miklcct at gmail dot com
This design in PHP is very counter-intuitive and error-prone.
I think when converting from string to boolean, any string, except empty string, should be converted
to true, including all of arrTestVars below.
------------------------------------------------------------------------
[2009-08-31 17:49:29] az at kreatiefer dot de
Description:
------------
When you cast a string variable to boolean type there are some cases in which the cast doesn't
work properly, i think.
Reproduce code:
---------------
$arrTestVars = array(
'0',
'-0',
'+0',
'0.0',
'0e0',
'0.0e0'
);
foreach($arrTestVars as $strTestVar) {
var_dump(
(bool)$strTestVar
);
}
Expected result:
----------------
// Expected Result => (bool)false, (bool)false, (bool)false, (bool)false, (bool)false,
(bool)false
All the tests above should be evaluated to false, because
(bool)0.0 === false
(bool)0e0 === false
and so on.
Now one has to use the workaround (bool)(int)'0.0' === false ...
Actual result:
--------------
// Actual Result => (bool)false, (bool)true, (bool)true, (bool)true, (bool)true, (bool)true
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=49426&edit=1