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

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

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

IF vs. SWITCH and which is more suitable for this job and why?

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
}

Switch statement validation

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".

using variables for the cases and a function for a switch?

In PHP I'd like to do this:
switch (function_foo($bar,$bar2)) {
case $fu:
*Do Stuff*
break;
case $fubar:
*Do Other Stuff*
break;
}
Is this a terrible idea? Will it work?
Using a function in the switch is OK : the function will be called, and will return a value -- which is the one that will be used for the case.
It's exactly the same as writing :
$my_var = function_foo($bar,$bar2);
switch ($my_var) {
// ...
}
Even if I prefer using a variable, so the code is easier to read.
And using variables in the case is something you don't see often ; but it works fine too ;-)
Quoting the manual page of switch :
The case expression may be any
expression that evaluates to a simple
type, that is, integer or
floating-point numbers and strings.
So, your code will work, as long as $fu and $fubar contain simple-type values.
Using a variable as a case value not often done (as far as I can tell from the code I read), probably because some other languages don't allow that (for instance, C doesn't allow that ; and the switch/case structure is borrowed from C) ; but it works :
$a = 1;
$b = 2;
switch (1) {
case $a: echo 'a'; break;
case $b: echo 'b'; break;
}
Will output :
a
Never tried a function as parameter to the switch, not sure (You should give it a try), however you can first store function return value in some variable and use that in switch eg:
$return_value = function_foo($bar, $bar2);
switch ($return_value) {
case $fu:
*Do Stuff*
break;
case $fubar:
*Do Other Stuff*
break;
}
According to the manual, a PHP switch statement is exactly like a series of if/else if statements (if every case ends with break). That means your technique should work. As long as the function names and variable names are readable, I can't think of any problems with it.
In some other languages, the switch statement is actually a performance improvement over if/else if statements, so you need to know the case values at compile time. It doesn't look like PHP does that kind of thing.
Its posibble yes and its called lambda, which are hidden functions
$lambda = function($a, $b) {
return $a * $b;
};
$return_value = function foo($bar, $bar2){ return $logic }
switch ($lambda(2,4)) {
case $fu:
*Do Stuff*
break;
case $fubar:
*Do Other Stuff*
break;
}

Multiple Separate Switch Statements

I have multiple switch statements in on one of the pages in order to pass different variables to the URL, as well as different case. I need these different switch statements because I need the different variables.
However, when I put a "default" in one of the switch statements, that default applies to every other switch statement and so when I use the variable of another switch statement in the URL, the default case of that other switch statement will appear on screen, along with the case of this switch statement.
All of my switch statements have one or more cases and I really cannot figure out how to get around this. Please may somebody help me?
Thanks in advance,
Calum.
This might be way off, but I think you need something like this:
if (isset($_POST['myvar'])) {
switch ($_POST['myvar'] {
case 1:
....
break;
default:
....
break;
}
} else if (isset($_POST['myvar2'])) {
switch ($_POST['myvar2'] {
case 1:
....
break;
default:
....
break;
}
}
Does that make sense?
make sure that you have a "break;" statement at the end of each of your cases, and that the default case is the last one. like this:
switch ($var) {
case 1: // do stuff 1;
break;
case 3: // do stuff 2;
break;
// ...
default: // do default stuff
}

Categories