php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #68346 Bug on switch in case 0
Submitted: 2014-11-05 09:36 UTC Modified: 2014-11-05 10:17 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: codingcarlos at gmail dot com Assigned:
Status: Not a bug Package: Testing related
PHP Version: Irrelevant OS: windows/linux
Private report: No CVE-ID: None
 [2014-11-05 09:36 UTC] codingcarlos at gmail dot com
Description:
------------
When a variable is stored via $_GET method (even when parsing to integer) and used in a switch, fails on case 0.

When you use it like: example.php?num=0 
You will get the result: "The number 0 is higer than 5." (Obiously fail)

But if you use 00 instead of 0: example.php?num=00 
You will get the result: "The number 00 is lower than 2." (Which is true)

It also works with " 0": example.php?num= 0
You will get the result: "The number 00 is lower than 2." (Which is true)

Test script:
---------------
$number = $_GET['num'];
// $number = intval($_GET['num']);
// $number = (int) $_GET['num'];

    switch ($number) {
        case ($number<2): 
            $result = 'lower than 2'; 
            break;
        case ($number<5): 
            $result = 'lower than 5'; 
            break;
        case ($number>=5): 
            $result = 'higer than 5'; 
            break; // Se mete aqui con nota = 10
    }
    echo "The number " . $number . " is " . $result . ".";

Expected result:
----------------
The number 0 is lower than 2.

Actual result:
--------------
The number 0 is higer than 5.

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-11-05 10:17 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2014-11-05 10:17 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 like saying "if (X == Y)". So what you've done is create
  if ($number == $number < 2) { ...
  } else if ($number == $number < 5) { ...
  } else if ($number == $number >= 5) { ...
  }
which is obviously not what you intended.

You can't do a "case < 2" but you can do
  switch (true) {
    case ($number<2):  // if (true == $number < 2)
    case ($number<5):  // if (true == $number < 5)
    case ($number>=5): // if (true == $number >= 5)
  }
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 07 08:01:28 2024 UTC