Switch statement validation - php

Does POST or GET data need to be validated if being thrown directly into a switch() statement? For example:
switch($_GET['input']) {
//...
}
???

If your switch contains real cases no, but if you do default you need to validate the $_GET if you use it in that case.
eg:
switch ($_GET['input']) {
case 'one':
echo "input is one";
break;
case 'two':
echo "input is two";
break;
default:
// here `$_GET['input']` need to be validated, escaped, checked if you use it to avoid XSS or SQL injections
echo $_GET['input'];
}

No, your case is basically the validation.

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.
Note that switch/case does loose comparision.
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
default:
echo "";
break;
}
?>
So, the short answer is "NO".

Related

How to loop through all cases in switch if they are all true

I have a switch statement with 3 cases,like this:
switch($date) {
case 1:
echo "";
break;
case 2:
echo "";
break;
case 3:
echo'';
break;
default:
echo '';
break;
}
And i am wondering,if there is a way to loop through all cases if they are all true.But with using break,because if i am not using it,the cases wont work properly.So is there a way???
You shouldn't use switch if you want to see if multiple things are true about the variable in question since the switch statement will cut out once one of the cases holds true (i.e. it won't continue to look to see if the other cases also apply to the variable).
If your goal is to test if multiple things are true regarding a variable, just use an if statement:
if ($date == X && $date == Y && $date == Z) {
// Do something since all the conditions are met
}
Another possibility is to "fall through" your cases like this:
switch ($variable) {
case 0:
// Do something to (some) variable to indicate this case applies
case 1:
// Do something to (some) variable to indicate this case also applies
case 2:
// Do something to (some) variable to indicate this case also applies
echo "WHATEVER YOU WANT TO ECHO"
break;
}

PHP switch statement with $_GET variables

Pages such as this: PHP switch case $_GET's variables and switch case $_GET's variable's values and others have helped, but I am at a loss as to why my switch statment does not work.
A user may be directed to my page with index.php?class=className&badge=badgeName or index.php?class=className or index.php?badge=badgeName or just plain old index.php
This code works just fine
if ($_GET["badge"] && $_GET["class"]) {
echo 'Badge and Class';
} elseif ($_GET["badge"] && !$_GET["class"]) {
echo 'Badge only';
} elseif (!$_GET["badge"] && $_GET["class"]) {
echo 'Class only';
} else {
echo 'No variables';
}
But I was trying to simplify with a switch statement, whereby all works well except for the default case:
switch ($_GET) {
case $_GET["badge"] && $_GET["class"]:
echo 'Badge and Class';
break;
case $_GET["badge"] && !$_GET["class"]:
echo 'Badge Only';
break;
case !$_GET["badge"] && $_GET["class"]:
echo 'Class only';
break;
default:
echo "No badge or class";
}
Any help appreciated.
You can try something like this:
switch (true) {
case ($i ==0):
echo '$i ==0';
break;
case ($i < 1):
echo '$i < 1';
break;
case ($i > 1):
echo '$i > 1';
break;
}
For your case:
switch (true) {
case ($_GET["badge"] && $_GET["class"]):
echo 'Badge and Class';
break;
case ($_GET["badge"] && !$_GET["class"]):
echo 'Badge Only';
break;
case (!$_GET["badge"] && $_GET["class"]):
echo 'Class only';
break;
default:
echo "No badge or class";
}
As the answer are in the link you gave:
You have to enclose the switch in a foreach() loop.
$_GET is simply an array, so you will have to make a for-each loop over it, as proposed in the link
foreach ($_GET as $key => $value) {
// Switch goes here
}
Then inside this for-each you can do switch, where you use the value of $key.
How you are going to tackle this one, I haven't figured out at the moment...
[EDIT]
I would stick with the if-elseif version - if you only have those two values to check for :)
I think you misunderstand the switch() statement. It is a special case of if... else if... else if for comparing a single variable to a possible set of values. You can't include conditions (expressions that evaluate to a boolean) in the case statements. See http://www.php.net/manual/en/control-structures.switch.php for examples.
EDIT:
I must take a minute to rail against the abuse of the switch statement that is as follows:
$a=1;
$b=2;
switch(true) {
case ($a==1):
echo "first test passed";
break;
case ($b==2):
echo "second test passed";
break;
}
This compares "true" to each of the boolean results of the expressions below. Both conditions are true, the first one executes, and the break; statement skips the second one. Technically functional, wildly misleading, and I'd throttle the guy who left me this code to debug. Absolutely abominable practice. By contrast, if you switch on a value like ($a) or ($a -3) and your case statements contain comparison values like 5 and 7, or "A" and "B", a good IDE will warn you that you have duplicate case statements. You can be sure that exactly one of the case statements passes the comparison. And the people who maintain your code in future won't have to hunt you down or curse your name. Please don't use switch() this way. If you need to do it like this, use if... else if... for readability. In this way it is obvious that the tests must be checked in order and the flow of execution will be transparent.

Can I use the same case value multiple times in a switch

Can I write a switch statement like this?
switch ($mood) {
case hungry :
case sad :
echo 'Eat a chocolate';
case sad :
echo 'Call Up your friend';
}
Is this a good practice?
EDIT : Removed the break statement, based on the comment.
It is technically possible to define multiple cases with the same value, but only the first case will get executed. So it's pretty much useless.
From the switch() documentation:
PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement.
Since the first case has a break in it, further cases won't be executed and the code will exit the switch() block.
Consider the following piece of code:
$var = 'sad';
switch ($var) {
case 'sad':
echo 'First';
break;
case 'sad':
echo 'Second';
break;
}
This will output First.
If you want to execute multiple statements if a condition is TRUE, then add them under the same case, like so:
switch ($var) {
case 'sad':
echo 'First';
echo 'Second';
break;
}

Switch Case in php Multiple Case run in function?

switch(n){
case "badge01":
case "badge02":
case "badge03":
case "badge04":
case "badge05":
//dosomething
break;
}
Hi above's switch case statement, I would like to use a function to run the multiple loop to generate the case's name, so can i know how to generate with function on a switch case statement like this?
switch(n){
case badgenameloop():
//dosomething
break;
}
And is it possible to do that?
Thanks and sorry for my bad English.
According to PHP Manual
The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.
I'm afraid you can Not have a Loop for a case statement, hence a waste of time trying.
You can do this for example:
function badgenameloop($key)
{
switch($key){
case "badge01":
case "badge02":
case "badge03":
case "badge04":
case "badge05":
echo "badge 1";
break;
}
}
function badgename2loop($key)
{
switch($key){
case "badge_2_01":
case "badge_2_02":
case "badge_2_03":
case "badge_2_04":
case "badge_2_05":
echo "badge 2";
break;
}
}
$key = "badge_2_01";
switch($key){
case badgenameloop($key): break;
case badgename2loop($key): break;
}

A multi-conditional switch statement?

This is something that I haven't seen in the PHPdoc for switch() so I'm not sure if it's possible, but I'd like to have a case which is multi-conditional, such as:
switch($this) {
case "yes" || "maybe":
include "filename.php";
break;
...
}
Is this valid syntax/is this even possible with a switch() statement?
Usually you'd just use case fall-through.
switch($this) {
case "yes":
case "maybe":
include "filename.php";
break;
...
}
Is this valid syntax/is this even possible with a switch() statement?
No and no. The expression will be evaluated as ("yes" or "maybe"), which will result in true. switch will then test against that result.
You want to use
case "yes":
case "maybe":
// some code
break;
Should be
switch($this) {
case "yes":
case "maybe":
include "filename.php";
break;
...
}
You can do this with fall-through:
switch ($this) {
case "yes":
case "no":
include "filename.php";
break;
}
Sure, just specify two cases without breaking the first one, like so:
switch($this) {
case "yes":
case "maybe":
include "filename.php";
break;
...
}
If you don't break a case, then any code for that case is run and continues on to execute additional code until the execution is broken. It will continue through all cases below it until it sees a break.

Categories