php - split switch cases in different files - php

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

Related

Is it posible to execute two cases of the switch?

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.

Is PHP's "alternative syntax" allowing this or is it the switch statement?

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

php switch statement limit

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

PHP Switch Case Url's

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);
?>

how do i add two values for one case using switch?

im trying to create a website using switch commands to navigate with the contents displayed in a table via echo content. everything works fine. but one of the pages consists of multiple pages. The address looks like this website/index.php?content=home etc.
but i want to make it like this for the page consisting multiple pages website/index.php?content=home&page=1
my index code:
<?php
switch($_GET['content'])
{
case "home":
$content = file_get_contents('home.php');
$pages = file_get_contents('pages/1.php'); //like this?
break;
case "faq":
$content = file_get_contents('faq.php');
break;
default:
$content = file_get_contents('home.php');
break;
}
?>
//some code
<?php echo $content; ?>
//some code
the home php:
<?php
switch($_GET['page'])
{
default:
case "1":
$page = file_get_contents('pages/1.php');
break;
default:
$page = file_get_contents('pages/1.php');
break;
}
?>
// some code
<?php echo $page; ?>
//some code
go to page etc.
but when i do it like this the echo command shows me the code of the home.php but not the one of the page i wanna load inside of it.
i appreciate any kind of help!
"default" must logically always come last in your switch, since it will match any input that hasn't already been matched by a previous "case" statement.
If you want to do certain actions for multiple values, you can do it like this:
switch ( $var ) {
case 'foo':
case 'bar':
// Do something when $var is either 'foo' or 'bar'
break;
default:
// Do something when $var is anything other than 'foo' or 'bar'
break;
}
Try using include() instead.
Also, as #Rob said, your second switch() statement is ill formatted. default: should always be last and is used as a "catch-all" for values you didn't specify earlier.
first of all, why don't you use include() instead of file_get_contents()?
Second of all: you could use your "manager" page in this way:
<?php
$myPage = $_GET['page'];
$myContent = $_GET['content']
switch($myContent){
case "mycontent":
case "home": include('/home.php');
if(!empty($myPage)){
include ('/pages/'.$myPage.'.php');
}
break;
default:
// do whatever you want
}
?>
Be careful of (as in steweb's example) including files based on user input, even with a prepended path — remember that there's the possibility of executing untrusted code. (Imagine if $_GET['page'] is set to ../../../some-evil-file.php, for example.)
To avoid this, it's easiest to use a whitelist:
$pages = array( 1, 2, 18, 88 );
switch ( $_GET['content'] ) {
case 'home':
if ( in_array( $_GET['page'], $pages ) ) {
include 'pages/' . $_GET['page'] . '.php';
} else {
// If an invalid page is given, or no page is
// given at all, include a default page.
include 'pages/1.php';
}
break;
}

Categories