How to add multiple condition cases inside Switch method? - php

Is there a way to include multiple cases inside a switch method in php?

The switch statement works by evaluating each case expression in turn and comparing the result to the switch expression. If the two expressions are equivalent, the case block is executed (within the constraints established by break/continue constructs). You can use this fact to include arbitrary boolean expressions as case expressions. For example:
<?php
$i = 3;
$k = 'hello world';
switch (true) {
case 3 == $i and $k == 'hi there';
echo "first case is true\n";
break;
case 3 == $i and $k == 'hello world';
echo "second case is true\n";
break;
} //switch
?>
This outputs:
second case is true
I don't use this sort of construction very often (instead preferring to avoid such complex logic), but it sometimes comes up where a complicated if-then statement might otherwise be used, and can make such snippets much easier to read.

What's wrong with simply nesting switches?
$i = 1;
$j = 10;
switch($i) {
case 2:
echo "The value is 2";
break;
case 1:
switch($j) {
case 10:
echo "Exception Case";
break;
default:
echo "The value is 1";
break;
}
break;
default:
echo "Invalid";
break;
}

Yes it is possible
Here is an example to start with
<?
$i = 1;
$j = 10;
switch($i) {
case "2":
echo "The value is 2";
break;
case ($i==1 && $j==10):
echo "Your exceptional Switch case is triggered";
break;
default:
echo "Invalid";
break;
}
?>

Related

Go to default case from another case in PHP

It is possible to go to default case from within some other case like this?
$a = 0;
$b = 4;
switch ($a) {
case 0:
if ($b == 5) {
echo "case 0";
break;
}
else
//go to default
case 1:
echo "case 1";
break;
default:
echo "default";
}
I tried to remove the else and was expecting that it would continue evaluating all following cases until default but it gets into case 1 then. Why is it so and how can I get to the default one?
Yes you can if you reorder the case statements:
switch ($a) {
case 1:
echo "case 1";
break;
case 0:
if ($b == 5) {
echo "case 0";
break;
}
default:
echo "default";
}
Why is it so:
it is defined, if you de not have a break statement the next case will be executed. If there is no more case, the default will be executed if one is defined
You could re-order the case statements to allow a fall through to the next option, but if there are several times you wish to do this it can become impossible or just very fragile. The alternative is to just more the common code into a function...
function defaultCase() {
echo "default";
}
switch ($a) {
case 0:
if ($b == 5) {
echo "case 0";
}
else {
defaultCase();
}
break;
case 1:
echo "case 1";
break;
default:
defaultCase();
}
I would suggest using a simple if / else as I mentioned in the comments.
However, here's another way you could do it using a switch statement, if that helps:
switch ([$a, $b]) {
case [0, 5]:
echo 'case 0';
break;
case [1, $b]:
echo 'case 1';
break;
default:
echo 'default';
}

PHP switch strange behavoiur with zero value and strings

Going immediately to the point:
in this code I expect the default case:
<?php
$a = 0;
switch ($a) {
case "one":
echo "one";
break;
case "two":
echo "two";
break;
default:
echo "default";
break;
}
?>
I get one instead.
here expect the zero case ("two"):
<?php
$a = 0;
switch ($a) {
case "one":
echo "one";
break;
case 0:
echo "two";
break;
default:
echo "default";
break;
}
?>
I get one instead.
That appens only with zero value because here I get correctly default:
<?php
$a = 1;
switch ($a) {
case "one":
echo "one";
break;
case "two":
echo "two";
break;
default:
echo "default";
break;
}
?>
but here I get correctly zero:
<?php
$a = 0;
switch ($a) {
case 1:
echo "one";
break;
case 0:
echo "zero";
break;
default:
echo "default";
break;
}
?>
Why?

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!"?
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";
}
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;
}
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.

switch statement with two variables at a time

Could someone suggest the best way to have the following switch statement? I don't know that it's possible to compare two values at once, but this would be ideal:
switch($color,$size){
case "blue","small":
echo "blue and small";
break;
case "red","large";
echo "red and large";
break;
}
This could be comparable to:
if (($color == "blue") && ($size == "small")) {
echo "blue and small";
}
elseif (($color == "red") && ($size == "large")) {
echo "red and large";
}
Update
I realized that I'll need to be able to negate ($color !== "blue") and compare as opposed to equating variables to strings.
Using the new array syntax, this looks almost like what you want:
switch ([$color, $size]) {
case ['blue', 'small']:
echo 'blue and small';
break;
case ['red', 'large'];
echo 'red and large';
break;
}
You can change the order of the comparison, but this is still not ideal.
switch(true)
{
case ($color == 'blue' and $size == 'small'):
echo "blue and small";
break;
case ($color == 'red' and $size == 'large'):
echo "red and large";
break;
default:
echo 'nothing';
break;
}
Doesn't work. You could hack around it with some string concatentation:
switch($color . $size) {
case 'bluesmall': ...
case 'redlarge': ...
}
but that gets ugly pretty quick.
Found at http://www.siteduzero.com/forum/sujet/switch-a-plusieurs-variables-75351
<?php
$var1 = "variable1";
$var2 = "variable2";
$tableau = array($var1, $var2);
switch ($tableau){
case array("variable1", "variable2"):
echo "Le tableau correspond !";
break;
case array(NULL, NULL):
echo "Le tableau ne correspond pas.";
break;
}
?>
Your other option (though not pretty) is to nest the switch statements:
switch($color){
case "blue":
switch($size):
case "small":
//do something
break;
break;
}
var $var1 = "something";
var $var2 = "something_else";
switch($var1.$var2) {
case "somethingsomething_else":
...
break;
case "something...":
break;
case "......":
break;
}

Switch evaluations

I recently got into an argument over how switch handles comparisons, and need help settling it.
If I write a switch such as:
switch ($x){
case ($x > 5):
echo "foo";
break;
case ($x < 5):
echo "bar";
break;
default:
echo "five";
break;
}
Which if statement is it equivalent to? A or B?
// A
if ($x > 5) {
echo "foo";
} elseif ($x < 5) {
echo "bar";
} else {
echo "five";
}
// B
if ($x == ($x > 5)) {
echo "foo";
} elseif ($x == ($x < 5)) {
echo "bar";
} else {
echo "five";
}
To everyone, let me clarify:
It is equivalent to B.
It is not "both", it is not sometimes its one, sometimes it is the other, it is always B. To understand why you sometimes see results that indicate that it might be A, you need to understand how type coercion works in PHP.
If you pass in a falsey value to the "argument" of switch and you use expressions in your cases that result in a boolean value, they will only match if your expression evaluates to FALSE.
switch is basically a huge if/elseif tree that performs loose comparisons (== instead of ===) between the value passed to switch (the left side of the expression) and the expression in the cases (the right side).
This can be proved quite nicely with a variation on your code:
$x = 0;
switch ($x) {
case $x > -1: // This is TRUE, but 0 == FALSE so this won't match
echo "case 1";
case $x == -1: // This is FALSE, and 0 == FALSE so this will match
echo "case 2";
}
And if we convert that to the two if/elseif trees:
A:
$x = 0;
if ($x > -1) {
// It matches here
echo "case 1";
} else if ($x == -1) {
// and not here
echo "case 2";
}
B:
$x = 0;
if ($x == ($x > -1)) {
// It doesn't match here
echo "case 1";
} else if ($x == ($x == -1)) {
// ..but here instead
echo "case 2";
}
Your example is equivalent to B.
If you want to use comparison into your switch (and be equivalent to A), you could write this:
switch (true) { // Use true instead of $x
case ($x > 5):
echo "foo";
break;
case ($x < 5):
echo "bar";
break;
default:
echo "five";
break;
}
That switch case is equivalent to B
Edit :
If we take for example that $x is equal to 0 :
$x > 5 will evaluate to false (and 0 evaluates to false too), so the first if will print bar, but the second one will print foo.
The switch will be transformed to something like this :
switch ($x){
case false:
echo "foo";
break;
case true:
echo "bar";
break;
default:
echo "five";
break;
}
and that will print foo (same as B)
Edit 2 :
I tried it so that gave me :
with $x = 0 => switch (foo), if A (bar), if B (foo)
with $x = 5 => switch (five), if A (five), if B (five)
with $x = 7 => switch (foo), if A (foo), if B (foo)

Categories