php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #49426 Logic error in boolean cast from string
Submitted: 2009-08-31 17:49 UTC Modified: 2016-12-19 09:26 UTC
Votes:5
Avg. Score:3.8 ± 1.0
Reproduced:4 of 5 (80.0%)
Same Version:1 (25.0%)
Same OS:1 (25.0%)
From: az at kreatiefer dot de Assigned:
Status: Wont fix Package: Scripting Engine problem
PHP Version: * OS: *
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2009-08-31 17:49 UTC] 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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-01-01 15:49 UTC] jani@php.net
-Summary: logic error in boolean cast from string +Summary: Logic error in boolean cast from string -Package: Feature/Change Request +Package: Scripting Engine problem -Operating System: Ubuntu 9.04 +Operating System: * -PHP Version: 5.3.0 +PHP Version: *
 [2016-12-19 09:03 UTC] 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.
 [2016-12-19 09:26 UTC] requinix@php.net
-Status: Open +Status: Wont fix
 [2016-12-19 09:26 UTC] requinix@php.net
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.
 
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Sat May 28 03:04:04 2022 UTC