Page 1 of 1
php switch vs. If/else - when to use it
Posted: Wed Aug 15, 2007 10:27 am
by nykoelle
I'm trying to improve my code and 'optimize it', figure out when in my code I should use a switch and when to do an if statement.
example, I had:
Code: Select all
$site_value = $_SESSION['site'];
if ($site_value=="csi")
{
$_SESSION['styled_site'] ="Administrator";
}
else if ($site_value=="beta")
{
$_SESSION['styled_site'] = "The BETA";
}
else if ($site_value=="hpcsd")
{
$_SESSION['styled_site'] = "Hyde Park";
}
and I did some research on a switch from php.net and here and found:
In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.
so now I changed my code to:
Code: Select all
switch ($_SESSION['site']) {
case "csi":
$_SESSION['styled_site'] ="Administrator";
break;
case "hpcsd":
$_SESSION['styled_site'] = "Hyde Park";
break;
}
I still tend to use a lot of if statements, and am trying to find a sort of rule of thumb as to when to use an if/else and when to use a switch. Is my usage here correct? If so why and what is the reason you should use one over the other (less resources, etc?). And is there any benefit to not making a variable out of $_SESSION['site'] and just referring to it directly?
thanks <3
(and sorry if this is in the wrong forum)
Posted: Wed Aug 15, 2007 10:42 am
by CoderGoblin
I like switch for readability if more than about 3 ifs would be needed. You should also notice the following in the manual..
... In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster...
Posted: Wed Aug 15, 2007 11:07 am
by superdezign
You should look at switches as a way to organize if statements if they are all looking at the exact same value. Also, switches are useful when you need to allow multiple outcomes to share an outcome, or portions of an outcome. For example, here's using a switch to show different level users everything at their level and beneath:
Code: Select all
switch ($currentUser->getUserPermissions()) {
case AUTH_ADMIN:
$this->showAdminSection();
case AUTH_MODERATOR:
$this->showModeratorSection();
case AUTH_STAFF:
$this->showStaffSection();
case AUTH_USER:
$this->showUserSection();
break;
default:
echo 'You should really log in. Go on.';
}
Posted: Wed Aug 15, 2007 12:23 pm
by nykoelle
so with your switch it hits every case that it matches until it hits the break?
so it reads into every case as soon as it hits one it matches. so what if you had somethign like:
Code: Select all
case 1:
echo $something;
case 2:
echo $something2;
break;
case3:
echo $something3;
case4:
echo $something4;
break;
so if something matched case 1, would it hit 2 and then stop? and then if something hit 3 it would hit 3 and 4 then stop? What would be the impact if there wans't a break at the end of case4 or not anywhere even?
Posted: Wed Aug 15, 2007 12:29 pm
by Benjamin
In all the code I have every written, I have probable used elseif less than 5 times.
Re: php switch vs. If/else - when to use it
Posted: Wed Aug 15, 2007 12:40 pm
by Christopher
nykoelle wrote:so now I changed my code to:
Code: Select all
switch ($_SESSION['site']) {
case "csi":
$_SESSION['styled_site'] ="Administrator";
break;
case "hpcsd":
$_SESSION['styled_site'] = "Hyde Park";
break;
}
I don't think I would use a control structure at all in this case. I think better would be:
Code: Select all
$default_site = 'csi';
$sites = array(
"csi"=>"Administrator",
"hpcsd"=>"Hyde Park",
);
if (array_key_exists($_SESSION['site'], $sites)) {
$_SESSION['styled_site'] = $sites[$_SESSION['site']];
} else {
// deal with error condition
$_SESSION['styled_site'] = $sites[$default_site];
}
The you could separate the allowed values from the actual assignment (put the values in the configuration or even in a database). And you don't need to change the assignment code when he list changes -- only update the array.
Re: php switch vs. If/else - when to use it
Posted: Wed Aug 15, 2007 12:56 pm
by superdezign
I think arborint meant to use array_key_exists().
Posted: Wed Aug 15, 2007 1:24 pm
by Christopher
Thank superdezign ... I fixed the code.
I need you to look through all my code!

Posted: Wed Aug 15, 2007 3:46 pm
by superdezign
arborint wrote:Thank superdezign ... I fixed the code.
I need you to look through all my code!

Hehe, I always seem to feel the need to run examples in my head, even if they don't really apply to me.
Posted: Thu Aug 16, 2007 1:28 pm
by nykoelle
I hadn't thought of using an array at all to be honest.
Though, can you explain
why using an array over a switch is functionally better? I'm trying to learn how to develop these sorts of things properly.
thanks again for the help, I know I'm being a bit difficult

Posted: Thu Aug 16, 2007 4:01 pm
by Christopher
nykoelle wrote:I hadn't thought of using an array at all to be honest.
Though, can you explain
why using an array over a switch is functionally better? I'm trying to learn how to develop these sorts of things properly.
thanks again for the help, I know I'm being a bit difficult

I sort of did at the end of my post. One goal of programming is to separate the code and the data in a organized manner. The solution I proposed does not require any code changes to the code that actually checks and sets the session. It could and probably should be implement now as a function. That would give it a clear interface. And the data can now come from any source so you could separate it out to where you keep you configuration information.
Code: Select all
function set_styled_site($sites, $default_site) {
if (array_key_exists($_SESSION['site'], $sites)) {
$_SESSION['styled_site'] = $sites[$_SESSION['site']];
} else {
// deal with error condition
$_SESSION['styled_site'] = $sites[$default_site];
}
}
$default_site = 'csi';
$sites = array(
"csi"=>"Administrator",
"hpcsd"=>"Hyde Park",
);
set_styled_site($sites, $default_site);
That just follows the basic goals of modular programming.
Posted: Thu Aug 16, 2007 5:45 pm
by superdezign
nykoelle wrote:Though, can you explain why using an array over a switch is functionally better? I'm trying to learn how to develop these sorts of things properly.
Sounds to me like you may have the VERY common misconception about arrays. A lot of programmers (admittedly, "newer" programmers specifically) think of arrays as a 'waste of memory,' so to speak. This comes from books on C / C++ and online tutorials for other languages that state that arrays use up more memory than single variables. From there, they don't really explain arrays as anything more than a linked list of variables in memory.
What a lot of them fail to mention is the PURPOSE of arrays. Arrays are meant to organize your code into usable objects (even before OOP emerged) that can be utilized and traversed. It is meant to make the production process simpler and neater, and is encouraged. When you have data in that manner, an array makes that code easy to update, display, and easy to re-use in a similar situation. Portability and re-usability should be something you consider a lot in your programming.
We're beyond the days where arrays took up too much memory. Memory isn't nearly as much of a problem as it once was, so use it!
Posted: Fri Aug 17, 2007 8:07 am
by nykoelle
I actually had never heard of anything you said in in your first paragraph. I slept through my Java I class on arrays 5 years ago, hated OOP and Java in its horrific entirety then because my teacher was a ying yang. His answer to 'How does a bubble sort work?' was 'MAGIC!' then he changed the subject.
I'm going to have to read up on this more, it seems like a stylistic/standardization issue. Curious, are there standardization schools of thought like in XHTML with the semantic coding and whatnot? If so can you refer me to those sites? I know of all of the html ones, but none of the PHP ones. It would seem in my example though, I only need to assign the variable into a session once, then I'm never touching anything in the switch/elseif/array again. So the array wouldn't be necessary.
However, please do enlighten me on some of the php standardization sites, thx

Posted: Fri Aug 17, 2007 8:17 am
by superdezign
Beyond style, it's hard to standardize coding. There would be too many exceptions because you can do whatever you want to do with your code. They can't predict everything that you will make. Just keep in mind that first and foremost, you should care about you. Keep it as simple and easy to manipulate as possible.
Sometimes, people think of simple as something like the hard-coded switch statement, but if you think in terms of the future and the fact that YOU have to maintain the script, automation is what you're after.
You could rewrite the same script 50 times, or write a class that handles it and just send it a few variables 50 times. Of course, if the dynamic solution isn't easy for you to deal with, you don't have to.