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.
Related
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;
}
Here is my code I wanted to ask if there is a better way to do this? I'm going to need more "else if" options and I'm worried about performance
if($_GET['begin'] === 'yeg'){
} else if ($_GET['begin'] === 'deda') {
} else if ($_GET['begin'] === 'beara') {
} else if ($_GET['begin'] === 'eima') {
} else if ($_GET['begin'] === 'aba') {
}
You should use switch statement instead. A switch construct is more easily translated into a jump (or branch) table. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation. - #Judge Maygarden
Why the switch statement and not if-else?
$begin = $_GET['begin'];
switch ($begin):
case 'yeg':
//do something
break;
case 'deda':
//do something
break;
case 'beara':
//do something
break;
case 'eima':
//do something
break;
case 'aba':
//do something
break;
endswitch;
You can try to use a switch statement instead:
switch ($_GET['begin']) {
case 'yeg':
break;
case 'deda':
break;
// Yada yada, continue like this as much as needed.
}
I'm wondering whether it is possible to replicate this kind of check in a switch statement/case:
if(isset($_POST["amount"]) && (isset($_POST["fruit"]))) {
$amount = $_POST['amount'];
$fruit = $_POST['fruit'];
if($fruit == "Please select a fruit") {
echo "<script>alert('Required Field: You must choose a fruit to receive your total')</script>";
} else if(empty($fruit) or ($amount<=0) or ($amount>50)) {
echo "<script>alert('Required Field: You must enter an amount between 0-50g to receive your total')</script>";
} ... and further on
Note: I'm paying more attention to the && comparison that can be done simply in one IF, and whether this is possible to be done in a switch case and receive results like the nested if/else would. If it's not possible, why? and which method would be more efficient and why?
I would rather stick with If-Else If condition rather than converting it to Switch statement.
You have to realize the the switch statement only accepts one parameter:
switch($arg)
In your case you have amount as $_POST["amount"] and fruit as $_POST["fruit"].
Your first problem is how will you pass that 2 values on the switch statement.
You cannot use a switch for this case, since you are checking a condition (isset) of two variables which produces a boolean result. Well actually you could do a switch of this condition and switch in case of true to this code and in case of false to that code. But that would not make much sense imho.
In a switch you can just check ONE variable or expression and in the cases you execute the code of whatever the result of that switch evaluation was.
So no, you cannot do a switch with these nested ifs.
edit: to make this a bit more clear, a swicth is best used when you find yourself using multiple ifs on the same variable:
if ($var < 3)
{
// do this
}
elseif ($var < 6)
{
// do that
}
else
{
// do something other
}
Would be much better written:
switch ($var)
{
case < 3:
// do this
break;
case < 6:
// do that
break;
default:
// do somehting other
}
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;
}
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".