Page 1 of 1

Switch function with function in case statement?

Posted: Sat Mar 27, 2010 1:49 pm
by jraede
Currently my URL rerouting engine has a bunch of if-elseif-else statements that go through the various types of displays. However, I'm trying to reduce CPU usage and I've read that switch statements are much faster than if-else statements, so I'm trying to consolidate the rerouting engine into a switch statement. My problem is, in some of my if clauses, I have something like

Code: Select all

elseif($area = get_is_area($explode[2])) { $resourceID = $area;}
Is there a way to put that function in a case for a switch($explode[2]) ?

Re: Switch function with function in case statement?

Posted: Sat Mar 27, 2010 7:45 pm
by Alkis
Which is the value you are checking against other conditions? Is the $explode[2] expression, or the $area variable?

Re: Switch function with function in case statement?

Posted: Sat Mar 27, 2010 9:33 pm
by jraede
It's $explode[2];

Re: Switch function with function in case statement?

Posted: Sat Mar 27, 2010 10:25 pm
by Alkis
yes you can do it.

Code: Select all

switch($explode[2]){

    case "something":
      //do stuff...
    break;

    case 5:
      //do stuff...
    break;


}

Re: Switch function with function in case statement?

Posted: Sat Mar 27, 2010 10:29 pm
by jraede
That's not a function... I was asking for something like "case $area = get_is_area(explode[2])"

Re: Switch function with function in case statement?

Posted: Sat Mar 27, 2010 10:51 pm
by Alkis
Ok,
well the expression:
case $area = get_is_area(explode[2])

will either evaluate to true, or false. No other possible value. Unless you mean to check equality? -> case $area == get_is_area($explode[2])

Also write me a few lines on how you would use the switch block. Code.

Re: Switch function with function in case statement?

Posted: Sun Mar 28, 2010 4:02 am
by jraede
Yeah, I want it to evaluate to either true or false. If it's true, it'll return the database resource ID for that particular area, and I can do the URL rerouting. If not, then it's not an area, and I can continue.

The switch statement looks like this:

Code: Select all

switch($explode[2]) {
     case 'XXX':
          // do something
          break;
     case $area = get_is_area($explode[2]):
          // will this work?
          break;

}
I mean, I guess I could try this and see if it runs. Just wanted to see if it's feasible, or if there's a better way, before I did.

Re: Switch function with function in case statement?

Posted: Mon Mar 29, 2010 3:47 pm
by AbraCadaver
Gets kind of ugly using a switch like this, but it depends upon your other conditions. Here's a sample:

Code: Select all

switch(true) {
    case ($area = get_is_area($explode[2])):
        //do something
        break;

    case ($explode[2] == 'XXX'):
        //do something else
        break;
}