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.
Related
I am learning PHP. I have downloaded an open source project from a website and looking the workflow of each modules in that project. I noticed a switch case which is unfamiliar to me.
switch ($value) {
case 'student':
case StudentClass::getInstance()->getId();
return new StudentClass();
break;
case 'teacher':
case TeacherClass::getInstance()->getId();
return new TeacherClass();
break;
default:
break;
}
The above patch is what I looked.
When I give input:
$value = 'student';
It returns StudentClass instance.
If I give
$value = 'teacher';
then it returns TeacherClass instance.
If anyone explain the flow, it will be helpful to me to understanding PHP much better
Your string cases don't have break or return statements, so they "fall through" to the next case. Also, your breaks don't serve any purpose here.
I've added comments to your code to explain what's happening.
switch ($value) {
case 'student': // keeps going with next line
case StudentClass::getInstance()->getId();
return new StudentClass(); // handles both cases above
break; // unnecessary because of the return above
case 'teacher': // keeps going with next line
case TeacherClass::getInstance()->getId();
return new TeacherClass(); // handles both cases above
break; // unnecessary because of the return above
default:
break; // pointless, but handles anything not already handled
}
Also, PHP explicitly allows use of a semicolon (;) after a case, but it is not generally considered good style. From the docs:
It's possible to use a semicolon instead of a colon after a case...
Switch statement is used to perform different actions based on different conditions.
First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.
switch (n) {
case label1:
code to be executed if n=label1;
break; // if n=label1,break ends execution and exit from switch
case label2:
code to be executed if n=label2;
break; // if n=label2,break ends execution and exit from switch
case label3:
code to be executed if n=label3;
break; // if n=label3,break ends execution and exit from switch
...
default:
code to be executed if n is different from all labels;
}
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'.
my switch statement has about ten outcome, but some of them need 1/2 loops to check, so i can't write them within case(condition), so i've tried using more than one default case, is this possible?
<?php
switch(true) {
case 1:
break;
case 2:
break;
default:
echo "this text is never printed ??";
while(true) {
while(true) { // case 3
break 3;
}
break;
}
while(true) {
// case 4
break 2;
}
case 5:
break;
default:
while(true) {
// case 6
break 2;
}
case 7:
break;
}
?>
is this sort of thing possible, as my first default doesn't seem to be executing at all?!
thanks
You cannot have more than one default in a switch statement. Also, default should be at the end of of the switch after all the case statements.
What might be happening when your code is run through the PHP engine is that the parser is reading the switch statements into a hash map type data structure and each time the parser finds a default label, it's overwriting the existing entry in the hash map. So only last default label ends up in the data structure that gets used in execution.
No this isn't possible, you can't have more than one default case in a switch statement, you'll need to put additional logic into the single final case statement.
when the default case is reached it captures all conditions so later cases are not evaluated.
To answer your question - no, it is only possible to have one default and that at the end. I'm not sure whether you can place other cases after the default, but what I'm sure of is that they would never be reached...
EDIT:
Also, I don't see what you're trying to do there. What's the point? Could you explain a bit? We might be able to help you accomplish what you want to do
You can have only one default in a switch. Remember that Zend is not the only thing that parses PHP, you may confuse other parsers by not putting the default case as the very last part of the switch.
If "car" or "ferrari" as an input, it should print "car or ferrari". How can I achieve it?
<?php
$car ='333';
switch($car)
{
case car OR ferrari:
print("car or ferrari");
break;
case cat:
print("cat");
break;
default:
print("default");
break;
}
?>
Use two case clauses:
case 'car':
case 'ferrari':
print("car or ferrari");
break;
The explanation:
It is important to understand how the switch statement is executed in order to avoid mistakes. 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.
You can simply "fall through" the cases you want to handle equally:
<?php
$auto ='333';
switch($auto)
{
case car:
case ferrari:
print("car or ferrari");
break;
case kissa:
print("cat");
break;
default:
print("default");
break;
}
switch($car)
{
case car:
case ferrari:
print("car or ferrari");
break;
case cat:
print("cat");
break;
default:
print("default");
break;
}
Cases "fall through" until the first break statement. This also means that you don't need a break in the default case.
switch($car) {
case 'car':
case 'ferrari':
print("car or ferrari");
break;
case 'cat':
print("cat");
break;
default:
print("default");
break;
}
This is taking advantage of the 'fall-through' property of the switch() statement. Basically, a section doesn't stop at a case, it stops at a break (or other operation that exits the function).
I've taken the liberty of applying the indentation I prefer for switches, which makes them only use up one indent level, which I consider appropriate because, logically, the switch and its cases are all elements of the same construct. So using two indent levels within the switch conveys no useful information.
I dont' know if PHP supports this but in C, you could do something like this:
case car:
case ferrari:
print("car or ferrari");
break;
The idea is that code for handling the car case will keep running until it hits a break statement. As for style, it should be avoided.
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.