Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP switch and case logical control

It possible to have logical control on case ?

ie:

$v = 0;
$s = 1;

switch($v)
{
    case $s < $v:
        // Do some operation
        break;
    case $s > $v:
        // Do some other operation
        break;
}

Is there a way to do something similar ?

like image 441
KodeFor.Me Avatar asked Apr 14 '26 16:04

KodeFor.Me


1 Answers

The condition that is passed to switch is a value the cases are compared against. The condition (in your question $v) is evaluated once and then PHP seeks for the first case that matches the result.

From the manual (after Example #2), emphasis added:

The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement.

In your question switch ($v) is same as if you'd written: switch (0), because $v = 0. Then, your switch will try to find a case which equals to 0. And, just as @Kris said:

$s < $v evaluates to false, which triggers on the $v because it is 0 in here.


If you have to use conditions in case statements, your switch-condition should be a boolean, e.g.:

$v = 0;
$s = 1;

switch (true) {
    case ($s < $v):
        echo 's is smaller than v';
    break;

    case ($s > $v):
        echo 's is bigger than v';
    break;
}

Now your switch tries to seek the first case that evaluates to true, which in this case would be $s > $v.


Note that while the switch-condition is evaluated only once, cases are each evaluated in order:

$a = 1;

switch ($a) {
    case 2:
        echo 'two';
        break;
    case (++$a > 2):
        break;
    default:
        echo $a;
}

echoes '2' from default-case, because when comparing $a to "2" $a was 1 and the case is discarded; while:

$a = 1;

switch ($a) {
    case (++$a > 2):
        break;
    case 2:
        echo 'two';
        break;

    default:
        echo $a;
}

echoes 'two' from case '2' because ++$a > 2 increases $a but doesn't match $a.

default is a fallback and its position doesn't matter.

NB: the aforementioned switches are fugly and esoteric and are only provided as a proof-of-example.

like image 127
Jari Keinänen Avatar answered Apr 16 '26 06:04

Jari Keinänen