nick
nick

Reputation: 2783

PHP switch function doesn't recognize "less than 0"

$bytes = 0;
switch($bytes){
    case $bytes == 0:
        echo 'Equal to 0.';
    break;
    case $bytes < 0:
        echo 'Less than 0.';
    break;
}

This outputs "Less than 0."

Why?

Upvotes: 3

Views: 2874

Answers (3)

CoR
CoR

Reputation: 3914

An old question, but there's another way of using switch :) I found it on SitePoint!

switch (true) {

    case $bytes == 0:      // result of this expression must be boolean
        echo 'Equal to 0.';
    break;

    case $bytes < 0:     // result also must be boolean
        echo 'Less than 0.';
    break;

    default:
}

Explanation: if true == ($bytes == 0) or if true == ($bytes > 0) or default:
You can use switch (false) {} if you have many falsy results instead of x != y

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227270

switch statements don't work like that. When checking each case, the value is compared to the case value (using ==).

So, PHP is doing:

  • Does $bytes == ($bytes == 0)? Which is: $bytes == (true). This is false, so it's skipped.
  • Does $bytes == ($bytes < 0)? Which is: $bytes == (false). This is true, so it runs that block.

You need to use an if/else here.

$bytes = 0;
if($bytes == 0){
    echo 'Equal to 0.';
}
elseif($bytes < 0){
    echo 'Less than 0.';
}

Upvotes: 8

inVader
inVader

Reputation: 1534

You cannot use operators in your switch statements. It actually should be:

$bytes = 0;
switch($bytes){
    case 0:
        echo 'Equal to 0.';
    break;
    default:
        echo 'Something else';
    break;
}

Have a look at the full documentation: http://www.php.net/manual/en/control-structures.switch.php

Why does your sample result in 'less than zero'? Easy question: ($bytes < 0) evaluates to false, since it isn't. False is equivalent to 0 so it matches $bytes and falls into that case.

If you need to match certain ranges you are bound to use if-else-constructs.

Upvotes: 0

Related Questions