PHP switch() skipping breaks to apply extra logic - php

I have a flag that when passed to a switch statement needs different logic applied to it, three of the cases apply the same logic apart from one of those cases (out of the three) has an extra step.
Is this syntactically correct?
switch($foo)
{
case 1:
//do something
break;
case 2:
//do step 1
case 3:
case 4:
//do step 2
break;
}

Yes, your code is syntactically correct and will do what you've said in the comments.

Related

Switch case statement in PHP

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;
}

PHP switch() statement

Is this good practise ... ie, grouping the default case with another?
switch ($cond){
case 1:
...;
break;
case 2:
...;
break;
case 3:
default:
...;
break;
}
It makes perfect sense to do it that way.
Also, #Ian is correct, but in a limited scope. If you wanted additional functionality applied to case 3 you would leave it the way it is. As long as you don't break, it will go on to the next case.
It kind of makes case 3 redundant though, so I'd remove it and just leave it as default

What is the difference between Switch and IF?

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'.

Loops within Switch statement

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.

PHP: two values in the case of 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.

Categories