Page 1 of 1

Control Structure

Posted: Tue Sep 26, 2006 12:28 am
by Benjamin
What is the method for creating a control structure without using an else if, that would work as the following would work if switches supported expressions on a per case basis.

Code: Select all

switch (null)
{
    case $a = $x:
        echo 1;
    break;
    case $c = $x:
        echo 2;
    break;
}

Posted: Tue Sep 26, 2006 2:48 am
by GM
Isn't your example the equivalent of:

Code: Select all

switch($x) {
    case $a:
        echo 1;
    break;
    case $b:
        echo 2;
    break;
}
??

Posted: Tue Sep 26, 2006 2:50 am
by daedalus__
I think he was asking about something to that effect.

Posted: Tue Sep 26, 2006 2:58 am
by GM
Did I take the example too literally then? :?

In that case, I saw this example in the user notes of the manual:

Code: Select all

switch (TRUE){
    case ($v_BAL <= 0): //less then 0 , -0 
         echo $v_BAL;
    break;

    case ($v_BAL <= 10 AND $v_BAL >= 1): //less then 10 and greater then 1
         echo $v_BAL;
    break;

    default: //default
        echo $v_BAL;
    break;
}
Which seems pretty useless, as all three switches do the same thing, but it illustrates the point. Probably.

Posted: Tue Sep 26, 2006 3:01 am
by Benjamin
No, there is a third value, $c. I need something similar to a switch but that allows expressions.

Like,

Code: Select all

if $x = '15';
  // do something
break;
if $y = 'yellow'
  // do something else
break;
// etc..

Posted: Tue Sep 26, 2006 3:03 am
by GM
I edited my post above - does the switch(true) syntax do what you need?

Posted: Tue Sep 26, 2006 3:18 am
by Benjamin
No you can't use a comparison operator in a case. :(

Hmm maybe it does with (), I'll try that..

Yeah that works.. Awesome!

Thank you!

Posted: Tue Sep 26, 2006 8:20 am
by psurrena
Why would you not use an if / then? What's the advantage of switch?

Posted: Tue Sep 26, 2006 3:48 pm
by Benjamin
Just cleaner code in my opinion. I always prefer to use switches when possible. They are generally more efficient than elseif as well.

Posted: Wed Sep 27, 2006 1:50 am
by Christopher
Not sure if this is an answer to your question, but the OO pattern for implementing a switch is Chain of Responsibility. And warning -- there are two flavors of that pattern.

Posted: Wed Sep 27, 2006 3:35 am
by Benjamin
Well it's in a method inside of a class already, if that matters at all...

Posted: Wed Sep 27, 2006 5:49 am
by Jenk

Code: Select all

switch (true) // can also use false
{
    case ($a == $b):
        echo $a;
        break;

    case ($a != $b):
        echo $b;
        break;
}