Cleaner way to translate index into specified string? - php

Could I achieve this in a more cleaner way? Would be really appricated.
switch($vocation) {
case 1: $vocation = "Sorcerer"; break;
case 2: $vocation = "Druid"; break;
case 3: $vocation = "Paladin"; break;
case 4: $vocation = "Knight"; break;
case 5: $vocation = "Master Sorcerer"; break;
case 6: $vocation = "Elder Druid"; break;
case 7: $vocation = "Royal Paladin"; break;
case 8: $vocation = "Elite Knight"; break;
}
Thanks!
and sorry about the title couldnt figure out a better one

You can use an array instead of the switch statement.
$vocations = array("Sorcerer", "Druid" ...);
$vocationStr = $vocations[$vocation - 1];
Or
$vocations = array(1 => "Sorcerer", 2 => "Druid" ...);
$vocationStr = $vocations[$vocation];
Personally, I am against the reuse of $vocation to refer to two types (integers and String), as they are most likely two different concepts in your program.
I would also advise creating an Enum type for these values instead, but this depends on the context.

Well, depending on what you're using this for (not really sure as there is no context) one option is to have your vocations available in a configuration file (be it XML, text file, etc) that can be read in by the system on the fly. This way, if you ever want to add an additional vocation, you can just update the text file and you don't need to rebuild and/or redeploy your source.

Either using an array as already mentioned, or, at the very least, using constatants rather than the plain integers in the switch statement. So something like:
define("SORCERER", 1);
define("DRUID", 2);
...
define("RPALADIN", 7);
define("EKNIGHT", 8);
switch($vocation) {
case SORCERER: $vocation="Sorcerer"; break;
case DRUID: $vocation="Druid"; break;
...
case RPALADIN: $vocation="Royal Paladin"; break;
case EKNIGHT: $vocation="Elder Knight"; break;
}
That way adding new classes and ranks between classes is a little easier.

This gives a trap for initial values of vocation not found in your list.
$vocations = array(1=>"Sorcerer", 2=>"Druid", ...);
if (array_key_exists($vocation, $vocations)) {
$vocation = $vocations[$vocation];
} else {
$vocation = 'Not found';
}

Use an enumeration
http://it.toolbox.com/blogs/macsploitation/enums-in-php-a-native-implementation-25228

An array can work for sequential keys, but use an associative array (hash) otherwise.
%vocations = array("key1"=>"value1", "key2"=>"value2", ...);
$vocationVal = $vocations{$vocationKey};
EDIT: The above is a perl syntax, the php syntax is below:
$vocations = array(key1 => "value1", key2 => "value2", ...);
$vocationVal = $vocations[$vocationKey];

Another option that i haven't seen here is to keep the data in a table. It will help if the list becomes huge.
vocation_id vocation_name
1 sorcerer
2 druid
etc....
select vocation_name form vocations where vocation_id=3

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.

How to use switch case in Mustache template?

I'm using Mustache template in Core PHP to turn PHP pages to template. Now I want to use switch case in template like:
<?php
switch ($gift_card['FlagStatus']) {
case 'P':
echo "Pending";
break;
case 'A':
echo "Active";
break;
case 'I':
echo "Inactive";
break;
}
?>
what should be its similar Mustache translation?
thanks in advance
If you need to do more than just output a single value from the switch statement, the simplest workaround is to create a series of booleans, one for each state: isPending, isInactive, isActive etc and then use separate sections for each eventuality:
{{#isPending}}
Your gift card is pending. It will be activated on {{activationDate}}.
{{/isPending}}
{{#isActive}}
Your gift card is active. Its balance is ${{balance}}.
{{/isActive}}
{{#isInactive}}
Your gift card is inactive. Go here to reactivate it.
{{/isInactive}}
The switch statement would go in the php, for example:
In the php
$card_status = null;
switch ($gift_card['FlagStatus']) {
case 'P':
$card_status = "Pending";
break;
case 'A':
$card_status = "Active";
break;
case 'I':
$card_status = "Inactive";
break;
}
render_template('giftcard_stuff', array('card_status'=>$card_status);
In the template
<div>The status of this gift card is: {{card_status}}</div>
Things get more tricky when you're trying to do things like put flags like that into a dropdown, in which case you'd have to write out the array in advance, like:
$status_dropdown = [
['flag_display'=>'Pending', 'flag'=>'P'],
['flag_display'=>'Active', 'flag'=>'A'],
['flag_display'=>'Inactive', 'flag'=>'I'],
];

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

php - split switch cases in different files

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

Categories