PHP script that I'm using contains the switch statement and break to prevent the code from running into the next case automatically:
if (!isset($a)) $a = '';
switch($a)
{
case 1:
default:
// some code
break;
case 2:
// some code
break;
case 3:
// some code
break;
}
How can I prevent users to write in URL as "$a" some number that does not exist in php switch statement?
For example, in this example above, if someone writes as a url indes.php?a=5 should get a message that the link is not correct. What is the best way to do that?
Another thing that interests me, is there any limit on the number of switch statements that it is wise to use on one page or can the size of that page can cause the problem if it is to too large?
Add this to the end of the switch.
default:
echo 'not correct';
break;
From php docs:
A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
http://php.net/manual/en/control-structures.switch.php
Add the default case.
default:
echo 'Invalid Option';
break;
And there is no limit for the cases in switch.
Update:
No matter what ever the size of the page is. But surly it depends on the script or code written inside the cases. It it is time consuming than that will effect.
The placement of your default tag might be causing an issue, but I'm not 100% sure of this:
if (!isset($a)) $a = '';
switch($a)
{
case 1:
default:
// some code
break;
case 2:
// some code
break;
case 3:
// some code
break;
}
The individual case statements execute whenever there is a match with $a. For example if the user submitted 3 (thus $a==3), then case 3 would execute. It will continue to execute until the break; statement is hit. The default block is only executed if no case statements match the value contained in $a.
For example if the user submitted 5 (thus $a==5), there is no case 5: so the default block would be executed. Thusly, it's usually a standard practice to place your default: block at the end of your switch statement as follows to show that if no case statements match the condition, it will be executed last.
if (!isset($a)){
$a = '';
}
switch($a)
{
case 1:
//some code
break;
case 2:
// some code
break;
case 3:
// some code
break;
default:
//code displayed when $a does not match any case statements
}
Hope that helps. Also, switch statements execute quite fast, they are basically similar to nested if statements. Thus there is no limit really, however, code optimization is always something you should strive for.
Your switch statement break because your using wrong structure of switch, check complete switch statement reference here
<?php
$i = 1;
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo 'no case match';
break;
}
?>
Related
I have something like this
switch($m){
case 1:
some code
break;
case 2:
some code
break;
case 3:
some code
break;
}
I need that then case 2 executes it will go back and execute case 1. or then case 3 executes i need it to go back and execute case 1.
Is it possible to do?
Thank you!
If I understood correctly, something like this should work for you:
function duck($m)
{
switch($m){
case 1:
//some code
break;
case 2:
duck(1);
break;
case 3:
duck(1);
break;
}
}
duck(2);
Good luck!
It is possible if you set it up right:
switch($var){
case 1:
some code 1;
case 2:
some code 2;
break;
case 3:
some code 3;
default
some code 4;
break;
}
Basically, it will keep going down the flow of the switch til it reaches a break. So, in this example, case 2 will execute code 2, but case one will execute first code 1 THEN code 2, because there is no break. Same thing for case 3 and default: case 3 would hit both some code 3 and some code 4.
I wrote a switch statement in PHP a few days ago and it was executing multiple conditions at a time. I couldn't figure what went wrong until I noticed I accidentally wrote default; instead of break; after one of the conditions.
Once the switch statement found a matching case, it executed the code inside as well as the code inside all of the cases that followed it.
$number = 3;
switch($number){
case 1:
echo 'One';
default; // who needs break
case 2:
echo 'Two';
default;
case 3:
echo 'Three';
default;
case 4:
echo 'Four';
default;
case 5:
echo 'Five';
default;
default:
echo 'Other';
}
This returns ThreeFourFiveOther (http://codepad.org/37zvAPiW).
Keep in mind, PHP never returned an error for this. Does the logic of switch statements permit my code above or is it PHP's "alternative syntax"?
It works because PHP allows semicolon ; to be used the same way : in switch syntax, i.e.
switch($a) {
case 1; // semicolon
// foo
break;
}
is the same as
switch($a) {
case 1:
// foo
break;
}
therefore from the above perspective you just planted default very early and having no break caused snowball effect.
Default in each case is just normal command, and have nothing to do with default in 'else' branch.
When the case isn't terminated/break with break command, another cases are executed too. In this case it's the same as if you remove default commands from cases, because these defaults do nothing.
switch($number){
case 1:
echo 'One';
case 2:
echo 'Two';
case 3:
echo 'Three';
case 4:
echo 'Four';
case 5:
echo 'Five';
default:
echo 'Other';
}
It works if you do use break statements: http://codepad.org/mFjlaVxz
switch(1){
case 1: print 1; // prints 1 (as expected)
case 2: print 2; // prints 2 (even though match is not equal?)
case 3: print 3; // prints 3 (even though match is not equal?)
}
I know that most programming languages continue to execute each statement if you don't use break after each case expression match. But I'm confused as to why most languages execute a case block as a successful match on this second and third case statement.
Just to clarify:
I am aware of the behavior of the switch statement, but I don't understand the logic that it makes sense to execute a case block/statement as a successful match even though a match is not found.
UPDATE: I just updated the question to reflect most programming languages and not just PHP.
From the manual:
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.
switch(1){
case 1:
echo 1; // echos 1 (as expected)
break; // stop!!!
case 2:
echo 2; // won't get here
break;
case 3:
echo 3; //or here
break;
}
The reason it's that way is probably because PHP borrowed the syntax from C.
However the reason it was originally this way is it helps to reduce code duplication I suspect.
If you have an if like:
if($item == 'SOUP' || $item == 'FRIES'){
eat($item);
}elseif($item == 'JUICE'){
drink($item);
}else{
use($item);
}
If switches never followed through you would need 4 cases with 'SOUP' and 'FRIES' having the same logic, without this you can make the switch nicer:
switch($item){
case 'SOUP':
case 'FRIES':
eat($item);
break;
case 'JUICE':
drink($item);
break;
default:
use($item);
break;
}
I know that PHP continues to check the switch statement cases if you don't use break after each case
Seems like you didn't understand. You missed to use the break keyword:
switch(1){
case 1: echo 1; break;
case 2: echo 2; break;
case 3: echo 3; break;
}
Note that a case statement is like an entry point in the code. After a case condition matches the code will run through all cases until the break is reached.
To your update: Note that this behaviour is the same for PHP as for most programming languages including : C, C++, Java, Javascript, ActionScript, Pascal, ....
Why does the switch statement execute a case block even when a match
is not found?
If you do not use break, it will execute all the switches, which can be helpful sometimes. for example:
switch ( count ) {
default : puts ( " ++++.....+++ " ) ;
case 4: puts ( " ++++ " ) ;
case 3: puts ( " +++ " ) ;
case 2: puts ( " ++ " ) ;
case 1: puts ( " + " ) ;
case 0:;
}
So if count is 3 you get output:
+++
++
+
If 2, you get output
++
+
if 10, you get:
++++.....+++
++++
+++
++
+
So there are times when you want your switch to execute the other cases, once it finds what you want. Like the code above.
You could do this with else if, but it would be a lot more typing.
We currently use Switch case url config to help us with the navigation on some of our urls, Im not sure if there is an easier way to do it but i couldnt seem to find 1.
<?php if (! isset($_GET['step']))
{
include('./step1.php');
} else {
$page = $_GET['step'];
switch($page)
{
case '1':
include('./step1.php');
break;
case '2':
include('./step2.php');
break;
}
}
?>
Now this system works perfectly but the only snag we hit is if they type in xxxxxx.php?step=3 boom they just get a blank page and that should be correct as there is no case for it to handle '3' but what i was wondering is .. is there any php code i could add to the bottom that may tell it for any case other than those 2 to redirect it back to xxxxx.php ?
Thanks
Daniel
Use the default case. That is, change your switch to something like this:
<?php if (! isset($_GET['step']))
{
include('./step1.php');
} else {
$page = $_GET['step'];
switch($page)
{
case '1':
include('./step1.php');
break;
case '2':
include('./step2.php');
break;
default:
// Default action
break;
}
}
?>
The default case will be executed for every case which is not explicitly specified.
All switch statements allow a default case that will fire if no other case does. Something like...
switch ($foo)
{
case 1:
break;
...
default:
header("Location: someOtherUrl");
}
would work. You may, however, want to Google around for other, more robust and extensible, page dispatch solutions.
How about a different approach with something along the lines of:
<?php
$currentStep = $_GET['step'];
$includePage = './step'.$currentStep.'.php'; # Assuming the pages are structured the same, i.e. stepN where N is a number
if(!file_exists($includePage) || !isset($currentStep)){ # If file doesn't exist, then set the default page
$includePage = 'default.php'; # Should reflect the desired default page for steps not matching 1 or 2
}
include($includePage);
?>
I have a php file in which i am using a really very long switch case. I want to split the cases in different files (keep logically connected cases in 1 file).
EDIT: Sorry everyone it was my code that was causing problem. The switch case was working as expected.
file -> a.php
echo "<br>RES = ".test(1);
function test($value) {
switch($value) {
case (1 || 2):
include("b.php");
**return $temp;**
break;
default: echo "error";
return 3;
break;
}
}
file -> b.php
switch($value) {
case 1: echo "value is 1";
**$temp = 1;**
return 1;
break;
case 2: echo "value is 2";
**$temp = 2;**
return 2;
break;
}
How do i get proper result? if the switch case of b.php is in a.php file then everything works fine.Any idea/suggestion on how to do this?
If i add $temp (bold lines) then it works...
Thanks for help in advance.
Regards
Updated response to updated question:
modify "a.php" and prefix a return infront of the "b.php" include:
return include("b.php");
http://www.php.net/manual/en/function.include.php
Handling Returns: It is possible to
execute a return() statement inside an
included file in order to terminate
processing in that file and return to
the script which called it. Also, it's
possible to return values from
included files. You can take the value
of the include call as you would a
normal function. This is not, however,
possible when including remote files
unless the output of the remote file
has valid PHP start and end tags (as
with any local file). You can declare
the needed variables within those tags
and they will be introduced at
whichever point the file was included.
simple include()'s within your case/break sections?
switch($var)
{
case 1:
include('case_1.php');
break;
case 2:
include('case_2.php');
break;
default:
include('case_default.php');
break;
}
This is actually something that Scuzzy proposed (I have even left the same naming convention), but improved:
// list of files
$my_files = array(
'a' => 'case_1.php',
'b' => 'case_2.php',
'c' => 'case_3.php',
'd' => 'case_4.php',
);
// determine which one to load
if (array_key_exists($var, $my_files)) {
include($my_files[$var]);
} else {
include('case_default.php');
}
or even shorter ;) :
$f = array('a','b','c','d');
include((in_array($var,$f)?$var:'case_default').'.php');
switch($var)
{
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: //...
include('case_' . $var . '.php');
break;
default:
include('case_default.php');
break;
}