|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #79592 Converting string to bool when "0" passed
Submitted: 2020-05-12 21:14 UTC Modified: 2020-05-13 15:39 UTC
From: 6562680 at gmail dot com Assigned:
Status: Not a bug Package: Filter related
PHP Version: 7.3.17 OS: Win10
Private report: No CVE-ID: None
 [2020-05-12 21:14 UTC] 6562680 at gmail dot com
I know, i know...
"you should use strict_types()" and so...

But really guys, why, exactly, why string "0" will be converted to false while calling (bool) ?

Please :///

Once i found same joke while comparing two values on usort(), fixed... now i remember used everywhere (! $string) and confused... little bit.

Test script:
function (string $name) {
  if (! $name) {
    // nice one, junior, you'll lose "0" right here
    // please rewrite your project and use ('' !== $name) or be fired

    throw new \InvalidArgumentException('String should be not empty');

  // some code

Expected result:
(bool) 0 === false
(bool) "0" === true
(bool) (string) 0 === true

Actual result:
(bool) 0 === false
(bool) "0" === false
(bool) (string) 0 === false


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2020-05-12 21:18 UTC]
-Status: Open +Status: Not a bug
 [2020-05-12 21:18 UTC]
This is documented behaviour, if you want a reason why this behaves like this imagine it being converted to an integer first and then converted to a boolean (because in effect a boolean is just an integer that is 0 for false and anything else for true).
 [2020-05-13 13:58 UTC] 6562680 at gmail dot com
You know, guys, documentation is like exception - it is delayed uncoded solution for the problem.

Good application never thrown exception. But as one coder you cant hold in your mind all possible exceptions so you throw it for future fixing.

The community imagine "documentation" word like "we just write there is a bug and it is not a bug. we're done"
 [2020-05-13 14:00 UTC] 6562680 at gmail dot com

$var = '0';
empty($var); // true

Even there...
 [2020-05-13 15:05 UTC] bugreports at gmail dot com
come on and fix your expectations given nobody but you expects "0" and 0 which is practically the same when it comes to type juggling evaluate to true

0/1 is the same as true/false, with or without you when it comes too lose types
 [2020-05-13 15:10 UTC] bugreports at gmail dot com
> Damn,
> $var = '0';
> empty($var); // true

damn guess hwat - it's consistent

'0' == 0 == FALSE

nobody right in his mind expects anything else when it comes to and that you refuse to understand language basics by insist it's a bug is a hint that you should refrain from programming to be honest
 [2020-05-13 15:39 UTC]
The point is, that even if we wanted to change this, we can't for
backward compatibility reasons.

PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Thu Apr 22 12:01:23 2021 UTC