php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72087 case $var !== 0 return wrong answer (only with 0)
Submitted: 2016-04-23 16:44 UTC Modified: 2016-04-23 16:58 UTC
From: sklogika2 at gmail dot com Assigned:
Status: Not a bug Package: *Programming Data Structures
PHP Version: 5.6.20 OS: Centos7
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: sklogika2 at gmail dot com
New email:
PHP Version: OS:

 

 [2016-04-23 16:44 UTC] sklogika2 at gmail dot com
Description:
------------
In the code below I get result of "not zero" when I should get "zero"
Such case comparisons do not work properly only with 0, with other numbers it is ok




Test script:
---------------
$userId = 0;
switch ($userId) {
    case $userId !== 0:
        echo "not zero";
        break;
    case 'userIdKOZqAfk':
        echo "zero";
        break;
}

Expected result:
----------------
zero

Actual result:
--------------
not zero

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-04-23 16:46 UTC] sklogika2 at gmail dot com
I'm sorry instead of case 'userIdKOZqAfk': should be default:
But idea is about !=0
 [2016-04-23 16:58 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2016-04-23 16:58 UTC] requinix@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

"switch ($x) case $y" is the same as writing "if ($x == $y)". What you've written there is "if ($userId == ($userId !== 0))".

You should use

switch ($userId) {
  case 0:
    echo "zero";
    break;;
  default:
    echo "not zero";
    break;
}
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Dec 30 14:01:28 2024 UTC