I know this may be simple question but want to know every ones opinion on this.
what is the difference between switch and IF function in PHP?? What I can see is where ever "switch" function uses "IF" function also applies there..correct me if I am wrong..
Or any performance wise difference between two??
Or any performance wise difference between two??
Forget about the performance difference on this level- there may be a microscopic one, but you'll feel it only when doing hundreds of thousands of operations, if at all. switch is a construct for better code readability and maintainability:
switch ($value)
{
case 1: .... break;
case 2: .... break;
case 3: .... break;
case 4: .... break;
case 5: .... break;
default: .... break;
}
is mostly much more clean and readable than
if ($value == 1) { .... }
elseif ($value == 2) { .... }
elseif ($value == 3) { .... }
elseif ($value == 4) { .... }
elseif ($value == 5) { .... }
else { .... }
Edit: Inspired by Kuchen's comment, for completeness' sake some benchmarks (results will vary, it's a live one). Keep in mind that these are tests that run 1,000 times. The difference for a couple of if's is totally negligeable.
if and elseif (using ==) 174 µs
if, elseif and else (using ==) 223 µs
if, elseif and else (using ===) 130 µs
switch / case 183 µs
switch / case / default 215 µs
Conclusion (from phpbench.com):
Using a switch/case or if/elseif is almost the same. Note that the test is unsing === (is exactly equal to) and is slightly faster then using == (is equal to).
If you have simple conditions, like if something equates to something else, then a switch is ideal.
For example, instead of doing the following:
if($bla == 1) {
} elseif($bla == 2) {
} elseif($bla == 3) {
} etc...
It's better to do it like this:
switch($bla) {
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
default:
...
break;
}
Alternatively, if you have complex conditions, you should use an if/else.
I think that this is all a matter of opinion though - some people just don't use switch statements at all, and stick with if/else.
No, you are right.
There are not much difference between these statements.
You may use one you like.
Just bear in mind that if you have to use more than 3-4 consecutive conditions - that means you most likely have design faults.
Usually you can substitute such a statement with a loop or with more clear application design.
The Switch Case Statement is an alternative to the if/else statement, which does almost the same thing. The Switch Case Statement executes line by line or statement by statement in other words, and once PHP finds a case statement that evaluates to true, it executes the code corresponding to that case statement.
The fundamental difference between if/else and switch statements is that the if/else statement selects the execution of the statements based upon the evaluation of the expression in if statements, but the Switch Case Statement selects the execution of the statement often based on a keyboard command.
Don't forget, though, that a switch does not necessarily work as a simple if statement. Remembering that a switch does not require a break at the end of each case and leaving that break off allows you to 'fall through' to the next case, too, can allow some interesting and somewhat complex 'ifs'.
Related
What is the different between
switch (variable) {
case 'value':
# code...
break;
case 'value':
# code...
break;
}
and this one
switch (variable) {
case 'value':
# code...
continue;
case 'value':
# code...
continue;
}
It's really different result or just same?
This is a special case for PHP because, as stated by the official documentation:
Note: In PHP the switch statement is considered a looping structure
for the purposes of continue. continue behaves like break (when no
arguments are passed). If a switch is inside a loop, continue 2 will
continue with the next iteration of the outer loop.
So in essence it means there is no actual difference between your two examples. However for clarity I think it would be best to use break as that is the standard in other languages. Note also that you could use continue 2 (or 3, 4...) to advance to the next iteration of a loop if the switch is inside a loop (or more).
In PHP the above two codes work in same way. Here the break and continue statement prevent control going to next case. That is the continue acts just like break here. Also switch is intended to be executed only once. It's not a loop. Hence continue is not relevant here.
Note:If there is loop enclosing this switch statement then the result will be different.
Here is a simple example code with both the switch cases mentioned above
<?php
$variable = 20;
echo "Normal<br/>";
switch ($variable) {
case '20':
echo "twenty";
break;
case '21':
echo "twenty one";
break;
}
echo "<br/><br/>With Continue<br/>";
switch ($variable) {
case '20':
echo "twenty";
continue;
case '21':
echo "twenty one";
continue;
}
?>
When I execute above code I got following output
Normal
twenty
With Continue
twenty
How?
Working of break statement
Break statement causes code execution to come out of the block and execute next statements because of which switch statement will execute only one case statement and exit out of switch block without executing other case blocks.
Working of Continue statement
Continue statement in case of loops will cause loop to stop execution of current iteration of loop and go for next iteration of the loop(if any exists) but in case of switch statement it is considered as a loop statement but no next iterations causing exit switch statement.
We can have a switch statement without break statements too like this
<?php
$variable = 20;
echo "Normal";
switch ($variable) {
case '19':
echo "<br/>Nineteen";
case '20':
echo "<br/>twenty";
case '21':
echo "<br/>twenty one";
case '23':
echo "<br/>twenty three";
}
?>
The output of above code will be
Normal
twenty
twenty one
twenty three
i.e. executing all the case statements after the case where first match is found.
This question already has answers here:
Why was the switch statement designed to need a break?
(9 answers)
Closed 8 years ago.
I don't understand why a switch-case statement requires you to explicitly insert a break after each case. Isn't the whole point of it to stop once a case is made?
Can someone give me a circumstance where a case is found true but for some reason [you insert reason here] you still need the code block to execute through.
This is a vaild PHP switch-case statement
switch ($error) {
case 'empty':
$msg = 'Field cannot be empty.';
break;
case 'invalid':
$msg = "Field may only contain number.";
break;
}
This is a invaild PHP switch-case statement
switch ($error) {
case 'empty':
$msg = 'Field cannot be empty.';
case 'invalid':
$msg = "Field may only contain number.";
}
So is this break useless or does it serve a purpose in some situations?
Because that's just how it works - it's how the language was designed. Probably because that's how C did it.
The most common use is for two cases to be treated the same.
switch ($error) {
// Treat warnings and errors the same
case 'warning':
case 'error':
echo "Something went wrong.";
break;
}
I believe this question is a duplicate to this one, answered robustly by #Micahel Burr :
Many answers seem to focus on the ability to fall through as the reason for requiring the break statement.
I believe it was simply a mistake, due largely because when C was
designed there was not nearly as much experience with how these
constructs would be used.
Peter Van der Linden makes the case in his book "Expert C
Programming":
We analyzed the Sun C compiler sources to see how often the default
fall through was used. The Sun ANSI C compiler front end has 244
switch statements, each of which has an average of seven cases. Fall
through occurs in just 3% of all these cases.
In other words, the normal switch behavior is wrong 97% of the time.
It's not just in a compiler - on the contrary, where fall through was
used in this analysis it was often for situations that occur more
frequently in a compiler than in other software, for instance, when
compiling operators that can have either one or two operands:
switch (operator->num_of_operands) {
case 2: process_operand( operator->operand_2);
/* FALLTHRU */
case 1: process_operand( operator->operand_1);
break; }
Case fall through is so widely recognized as a defect that there's
even a special comment convention, shown above, that
tells lint "this is really one of those 3% of cases where fall through
was desired."
I think it was a good idea for C# to require an explicit jump
statement at the end of each case block (while still allowing multiple
case labels to be stacked - as long as there's only a single block of
statements). In C# you can still have one case fall through to another
- you just have to make the fall thru explicit by jumping to the next case using a goto.
It's too bad Java didn't take the opportunity to break from the C
semantics.
It's also used for combinatory conditions.
To give a somewhat useless example:
// manually total up a number by 1
$sum = 0;
switch ($number) {
case 4:
$sum += 1;
case 3:
$sum += 1;
case 2:
$sum += 1;
case 1:
$sum += 1;
}
This sets switch apart from exclusive if trees in that one case can be a superset of another, and reduces code duplication. If all your cases contain a break, then you can certainly transpose it into an if list. (switch is often just utilized for stylistic reasons).
A single statement can carry multiple case labels, as the following example shows where we are not using break:
switch($constant)
{
case 'a' :
case 'b' :
case 'c' :
case 'd' :
case 'e' :
case 'f' : hexcvt(c);
}
In this example, if constant-expression equals any letter between 'a' and 'f', the hexcvt function is called.
Which is the better and fastest methods : if or switch ?
if(x==1){
echo "hi";
} else if (x==2){
echo "bye";
}
switch(x){
case 1
...
break;
default;
}
Your first example is simply wrong. You need elseif instead of just else.
If you use if..elseif... or switch is mainly a matter of preference. The performance is the same.
However, if all your conditions are of the type x == value with x being the same in every condition, switch usually makes sense. I'd also only use switch if there are more than e.g. two conditions.
A case where switch actually gives you a performance advantage is if the variable part is a function call:
switch(some_func()) {
case 1: ... break;
case 2: ... break;
}
Then some_func() is only called once while with
if(some_func() == 1) {}
elseif(some_func() == 2) {}
it would be called twice - including possible side-effects of the function call happening twice. However, you could always use $res = some_func(); and then use $res in your if conditions - so you can avoid this problem alltogether.
A case where you cannot use switch at all is when you have more complex conditions - switch only works for x == y with y being a constant value.
According to phpbench.com, if/elseif is slightly faster, especially when using strict comparison (===).
But it'll only really matter if you want to shave off microseconds on a function that'll be called thousands of times.
General rule is use switch whenever the number of conditions is greater than 3 (for readability).
if / else if / else is more flexible (hence better), but switch is slightly faster because it just computes the condition once and then checks for the output, while if has to do this every time.
EDIT: Seems like switch is slower than if after all, I could swear this was not the case...
When using ==, performance of if ... elseif compared to switch is almost identically. However, when using ===, if ... elseif is about 3 times faster (according to: phpbench).
Generally, you should go with what is most readable and use switch when making more than 3 comparisons. If performance is a major concern and you don't need to make any type conversions, then use if ... elseif with ===.
It's depending on usage. If you have fxp status (online, away, dnd, offline...) its better use switch.
switch(status)
{
case 'online':
...
}
But if you wanna something like this
if ((last_reply.ContainsKey(name)) && (last_reply[name] < little_ago))
or
if (msg.ToString()[0] == '!')
its better use if else.
I found this post: https://gist.github.com/Jeff-Russ/2105d1a9e97a099ca1509de1392cd314 which indicates switch/case to be faster than if/elseif with ===.
They also indicate nested if statements which makes a lot more sense and also provide far better results.
Their times:
nested if/elseif === : 0.25623297691345 (NESTED IF)
switch/case : 0.33157801628113 (SWITCH CASE)
if/elseif with === : 0.45587396621704 (FLAT IF)
only if with === : 0.45587396621704 (ONLY IF)
Switch is faster than if because switch uses jump table and jump table is made by compiler during compile time and run by cpu/os. For ex if you have 100 cases and you will get your value in 100 th one so what do you think it will run all 99 conditions...no..it will directly jump to 100th one with the help of jump table..so how can we prove this?...if you write default statement at start and then run the program will you get default value,since it is at start? No..you will get your desired answer because of jump table..it knows where is default and where is your assigned value and it will directly take you to your desired answer..
Talking about which is better...
Every work that can be done in if can be done in switch..
But for lesser condition if is better and for more conditions switch..like upto 3 conditions if is good.. after that a good programmer uses switch..that's all
I belive the compiler will turn them into very similar, or maybe even identical code at the end of the day.
Unless you're doing something weird, don't try and do the optimisation for the compiler.
Also, developer time is generally more important than runtime (with the exception of games), so it'sbbetter to make its more readable and maintainable.
in my opinion the "if/else" is faster but not better than switch
but i prefer this:
echo ($x==1?"hi":($x==2?"bye":""));
if you have to do 1,2 cases like if/else if/else
What is the best practice to end an if...else statement without an else condition? Consider the following code:
$direction = $_POST['direction']; //Up or down
if ($direction == "up") {
code goes here...
}
elseif ($direction == "down") {
code goes here...
}
else {
//do nothing?
}
As you can see, there's only 2 condition; either up or down and the else statement doesn't really have a purpose unless you want it to display an error message.
Most of the time I see programmers simply put the else condition there but inserts a comment instead of any working code like this.
else {
//error messages goes here...
}
or just assume if it's not 'up' then everything else should be 'down' since there's only 2 condition. If a user inputs 'left' or 'right', it would still be considered as 'down'. I think this is somewhat inappropriate.
if ($direction == 'up') {
code goes here...
}
else {
code goes here...
}
I know that PHP would still work if we put if without else condition. But what if there is an elseif condition? In cases like these, what is the best practice if we want to maintain a strict if...else statement if we do not want to include any error messages or have any else conditions?
Thanks in advance.
There is no if...else statement.
There is only an if statement that can be extended with else and elseif operators.
So, the best practice on if statement without else condition is an if statement without an else condition:
if (condition) {
//some code
}
Frankly, there is no best practice. The best practice is just one that follows the program logic.
That's all
Don't write empty elses. This would just clutter up the code, and it's perfectly obvious what you meant.
In many cases, you can actually use the switch statement:
switch ($_POST['direction') {
case 'up':
// code ...
break;
case 'down':
// code ...
break;
default: // else
throw new Exception('Invalid direction value');
}
I think that if there's nothing to do on else, then there's no need for else block to exist in code. If else block is included, it means that it has a purpose to be there, so the code is incomplete yet, if it is empty.
This isn't something that can take a definite answer. Here's my take, it would be interesting to see what other opinions exist.
Scenario 1: Testing a boolean condition
This is the simplest case:
if (condition) {}
else {}
Specifying a condition as else if would be redundant, and it's really obvious to the reader what the code does. There is no argument for using else if in this case.
Scenario 2: Testing for a subset of infinite states
Here we are interested in testing for conditions A and B (and so on), and we may or may not be interested in what happens if none of them holds:
if (conditionA) {}
else if (conditionB) {}
else {} // this might be missing
The important point here is that there isn't a finite number of mutually-exclusive states, for example: conditionA might be $num % 2 == 0 and conditionB might be $num % 3 == 0.
I think it's natural and desirable to use a reasonable amount of branches here; if the branches become too many this might be an indication that some judicious use of OO design would result in great maintainability improvements.
Scenario 3: Testing for a subset of finite states
This is the middle ground between the first two cases: the number of states is finite but more than two. Testing for the values of an enum-like type is the archetypal example:
if ($var == CONSTANT_FOO) {}
else if ($var == CONSTANT_BAR) {} // either this,
else {} // or this might be missing
In such cases using a switch is probably better because it immediately communicates to the reader that the number of states is finite and gives a strong hint as to where a list of all possible states might be found (in this example, constants starting with CONSTANT_). My personal criteria is the number of states I 'm testing against: if it's only one (no else if) I 'll use an if; otherwise, a switch. In any case, I won't write an else if in this scenario.
Adding else as an empty catch-errors block
This is directly related to scenario #2 above. Unless the possible states are finite and known at compile time, you can't say that "in any other case" means that an error occurred. Seeing as in scenario #2 a switch would feel more natural, I feel that using else this way has a bad code smell.
Use a switch with a default branch instead. It will communicate your intent much more clearly:
switch($direction) {
case 'up': break;
case 'down': break;
default: // put error handling here if you want
}
This might be a bit more verbose, but it's clear to the reader how the code is expected to function. In my opinion, an empty else block would look unnatural and puzzling here.
I sometimes do it like this. I'm not worried that "left"
is interpreted as "down" because I always validate my input, in this case with preg_match('{^up|down$}', $direction). Inarguably a switch is more appropriate... but I dislike the verbose syntax.
if ($direction == "up")
{
// code goes here...
}
else //if ($direction == "down")
{
// code goes here...
}
I try not to write else. Ever. In my experience, using else results in less readable logic, especially when if/elses are being nested.
For assigning a var to either true or false (or any other simple this-or-that value), I always use:
$varx = false;
if ($my_codition_here === true) {
$varx = true;
}
When I have a bigger chunk of logic that you might consider "belongs" in the if/else, I make sure to structure my code so that if the condition is met, the function terminates, usually by returning:
if ($my_codition_here === true) {
// A reasonable amount of logic goes here
return $the_result_up_untill_here;
}
// All logic that would have been "else" goes here.
return $the_result_up_untill_here;
As phihag mentioned; use a switch statement when you consider elseif.
And as Your Common Sense already said, there is no best practise, but there are good practises, and I think this is one.
In PHP switch statements, does placing more common cases near the top improve performance?
For example, say the following function is called 1,000 times:
<?php
function foo_user ($op) {
switch ($op) {
case 'after_update':
//Some Stuff
case 'login':
//Some other Stuff
}
}
If in 990 of the 1,000 of the times the function is called the $op argument is 'login', would performance improve by having case: 'login' above case 'after_update': in the switch statement? For example, would the code after case 'after_update': be ignored if $op = login was passed?
I've run some informal tests on this idea, but the difference has been negligible -- perhaps because the code after case: 'login' and case 'after_update': are both trivial. I'd prefer to avoid setting up a more extensive test with non-trivial operations if someone knows the answer outright.
This is specifically a Drupal question, but I imagine it could be addressed by anyone who is familiar with optimizing PHP.
This is likely going to be called a micro optimisation. I don't believe there would be a large difference.
However, order does mean a lot to the logic of the switch case if you allow the cases to fall through, example
switch ($var) {
case 0:
case 1:
do_it();
break;
case 2:
do_it_else();
break;
}
The order is important, the case will fall through and execute any code until it hits a break.
I wouldn't be concerned about the speed of the switch case, unless you had say 100 possible cases. But if then, it'd be likely you should refactor your code.
You will need a whole lot more than 1000 cases to notice a difference, but yes, there is a difference. I wrote up a test:
function test_switch($value) {
$startTime = time() + microtime();
for ($i = 0; $i < 10000000; $i++) {
switch($value) {
case "abcdefg":
$j = $j + 1;
break;
case "hijklmno":
$j = $j + 1;
break;
}
}
$endTime = time() + microtime();
echo "Total time for argument $value: " . ($endTime - $startTime) . "<br>\n";
}
test_switch("abcdefg");
test_switch("hijklmno");
That is 10 million executions of the switch statement. The output is:
Total time for argument abcdefg: 3.99799704552
Total time for argument hijklmno: 5.38317489624
So there is a difference, but it won't be noticeable until you reach on the order of 10 million executions, depending on your processor of course.
If you do not use break; to close each statement PHP will continue to evaluate cases until the end of the switch block which may impact performance in a large enough block. The order then becomes important for getting the behavior you are looking for.
From PHP.Net:
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. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
I would caution against relying on this behavior though and use break; for each case as that will remove some ambiguity when you revisit the code later.
Usually, it's recommended to write the most likely case first, the second one next...
but like Alex wrote,
This is likely going to be called a
micro optimisation. I don't believe
there would be a large difference.