Nadishan
Nadishan

Reputation: 580

PHP- Switch case statement with conditional switch

Can i put conditional statement within switch statement. ex - switch ($totaltime<=13) Other than php how about other languages compatibility with it?

$totaltime=15;

switch ($totaltime<=13) {

case ($totaltime <= 1):
echo "That was fast!";
break;

case ($totaltime <= 5):
echo "Not fast!";
break;

case ($totaltime >= 10 && $totaltime<=15):
echo "That's slooooow";
break;
}

Edit

$totaltime=12; 
switch (false) { 
case ($totaltime <= 1): 
echo "That was fast!"; 
break; 
case ($totaltime <= 5): 
echo "Not fast!";
break;
case ($totaltime >= 10 && $totaltime<=13): 
echo "That's slooooow"; 
break; 
default: // do nothing break; 
} 

Gentleman in this case why alwyas show output as "That was fast!"?

Upvotes: 0

Views: 4125

Answers (3)

Switch only checks if the first condition is equal to the second, this way:

switch (CONDITION) {
    case CONDITION2:
        echo "CONDITION is equal to CONDITION2";
    break;
}

So you have to do it this way:

switch (true) {
    case $totaltime <= 1: #This checks if true (first condition) is equal to $totaltime <= 1 (second condition), so if $totaltime is <= 1 (true), is the same as checking true == true.
        echo "That was fast!";
    break;

    case $totaltime <= 5:
        echo "Not fast!";
    break;

    case $totaltime >= 10 && $totaltime<=13:
        echo "That's slooooow";
    break;
}

Instead of this i'll go for if-elseif statements. Is easier to understand at first sight:

if ($totaltime <= 1) {
    echo "That was fast!";
} elseif($totaltime <= 5) {
    echo "Not fast!";
} elseif($totaltime >= 10 && $totaltime<=13) {
    echo "That's slooooow";
}

Upvotes: 3

Barry
Barry

Reputation: 3733

Yes you can (except for the comparison within switch)

$totaltime=12;

switch (true) {

case ($totaltime <= 1):
echo "That was fast!";
break;

case ($totaltime <= 5):
echo "Not fast!";
break;

case ($totaltime >= 10 && $totaltime<=13):
echo "That's slooooow";
break;

default:
// do nothing
break;
}

Upvotes: 1

Matan Hafuta
Matan Hafuta

Reputation: 605

Yes you can, from the PHP's switch documentation:

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values

When the case has constant value it's just like saying, case value == switch value, but you can have more complex expressions for a case.

Upvotes: 0

Related Questions