[thelist] php SWITCH vs ELSE IF
Mattias Thorslund
mattias at thorslund.us
Mon Apr 24 10:27:07 CDT 2006
Well, one difference is that your example will execute the is_page()
function up to seven times while the "switch" statement would execute a
similar function just once. If is_page() is a costly function, it could
affect performance noticeably. I suspect all your function does is to
compare some query string value with the parameter supplied--that
wouldn't be very costly at all.
I prefer the "switch" statement over "else if" when the method of
evaluation is the same in each case, such as in your example. Notice
that is_page() would need to be re-written to return the 'type' of page.
switch(get_page_type()){
case 'miscellaneous':
echo $misc;
break;
case 'associates':
echo $misc;
break;
//fill in the rest here...
default:
die('unknown page type');
break;
}
I might use the "else if" construct if the evaluations are different in
each step, but then "nested ifs" are often easier to read.
FWIW,
Mattias
Mark Mckee wrote:
> hi all
>
> I have written a short code to display a certain menu depending on which
> page it is on. the code works fine and I do get my desired results.
>
> i am using an ELSE IF statement and would like to know if this would be
> better than using a switch statement.
>
> sorry if this is a simple question but i was unable to find the answer
> with google and php websites.
>
> thanks in advance.
>
> the code:
>
> <?php
> if (is_page('miscellaneous'))
> {
> echo $misc ;
> }
> elseif (is_page('associates'))
> {
> echo $misc ;
> }
> elseif (is_page('downloads'))
> {
> echo $misc ;
> }
> elseif (is_page('gallery'))
> {
> echo $misc ;
> }
> elseif (is_page('reviews'))
> {
> echo $misc ;
> }
> elseif (is_page('xbox'))
> {
> echo $misc ;
> }
> elseif (is_page('moto-gp3'))
> {
> echo $misc ;
> }
> ?>
>
>
More information about the thelist
mailing list