How to use switch case in Mustache template? - php

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'],
];

Related

Can you use a if statement inside a switch

so I'm trying to make my own MVC website, I figured the best way to learn PHP better and tackle the big MVC issue is to start a full project. The thing is, I'm stuck at the router, I can't figure out how best to write it, I think this may be a good way at least for the moment but I'm not sure if it is a ..viable one. I was basically thinking of calling the right controller according to the switch case and then if there is a second url param(I've assumed it would be the id of a article for now) to call a method calling a single article and if there isn't a second param to call a method that calls all articles, but I would like to know if this is a bad way of doing it.
function call($controller, $id='') {
switch($controller) {
case '':
break;
case 'pages':
$controller = new PagesController();
break;
case 'articles':
require_once('controllers/' . $controller . 'Controller.php');
require_once('models/articles.php');
$controller = new ArticlesController();
if(!$id){
$controller->{ "blog" }();
}else{
$controller->{ "article" }($id);
}
break;
default:
header("HTTP/1.0 404 Not Found");
include('/views/404.php');
exit;
break;
}
}
P.S. For now I'm only working with the articles case, that's why the first case only breaks without doing anything and such. Thanks in advance.
Sure can, see the example below (this is proof of concept and not tested).
switch ($controller) {
case 'pages':
break
case 'articles':
if ($Apples != $Pears)
{
$Tomatoes="Red";
}
case "52":
case "109":
case "110":
//do nothing and exit from switch
break;
default:
if ($a == $b)
{
$c = "cats!";
}
break;
}
Note that you can also use a switch inside a switch, just like nested if statements.
If you have only 2 or 3 option then you can use if else otherwise use nested switch.
You can use if in switch also switch in another switch.

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.

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

Cleaner way to translate index into specified string?

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

Categories