PHP switch case more than one value in the case - php

I have a variable that holds the values 'Weekly', 'Monthly', 'Quarterly', and 'Annual', and I have another variable that holds the values from 1 to 10.
switch ($var2) {
case 1:
$var3 = 'Weekly';
break;
case 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4:
$var3 = 'Quarterly';
break;
case 5:
$var3 = 'Quarterly';
break;
// etc.
}
It isn't beautiful, because my code has a lot of duplicates. What I want:
switch ($var2) {
case 1, 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4, 5:
$var3 = 'Quarterly';
break;
}
How can I do it in PHP?

The simplest and probably the best way performance-wise would be:
switch ($var2) {
case 1:
case 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4:
case 5:
$var3 = 'Quarterly';
break;
}
Also, possible for more complex situations:
switch ($var2) {
case ($var2 == 1 || $var2 == 2):
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case ($var2 == 4 || $var2 == 5):
$var3 = 'Quarterly';
break;
}
In this scenario, $var2 must be set and can not be null or 0

switch ($var2) {
case 1 :
case 2 :
$var3 = 'Weekly';
break;
case 3 :
$var3 = 'Monthly';
break;
case 4 :
case 5 :
$var3 = 'Quarterly';
break;
}
Everything after the first matching case will be executed until a break statement is found. So it just falls through to the next case, which allows you to "group" cases.

If You're reading this and the year is 2021 and beyond, You're also using PHP > 8.0, you can now use the new match expression for this.
this could be
$var3 = match($var2){
1, 2 => 'Weekly',
3 => 'Monthly',
4, 5 => 'Quarterly',
default => 'Annually',
};
Please note that match does identity checks, this is the same as === compared to switch equality check which is ==.
read more about match expression here

Switch is also very handy for A/B testing. Here is the code for randomly testing four different versions of something:
$abctest = mt_rand(1, 1000);
switch ($abctest) {
case ($abctest < 250):
echo "A code here";
break;
case ($abctest < 500):
echo "B code here";
break;
case ($abctest < 750):
echo "C code here";
break;
default:
echo "D code here";
break;

You could use array to store you match groups; like:
<?php
$names = array('Ian', 'Jack', 'Fred', 'Ismail');
$name = 'Vladimir';
switch ($name) {
case (in_array($name, $names)):
echo '<p> Welcome ' . $name . '</p>';
break;
default:
echo '<p>' . $name . ' is a stranger to me?</p>';
}
?>

function bankRemark()
{
$this->db->select('id,status,funding_dt,date,remarks1');
$this->db->from($this->db_sdip);
$this->db->where("amc_remark != '' ");
$query = $this->db->get();
// echo $this->db->last_query();die;
if($query->num_rows() > 0)
{
$data = $query->result();
foreach($data as $val)
{
$id = $val->id;
$status = strtoupper($val->status);
$funding_dt = $val->funding_dt;
$date = $val->date;
$remarks1 = $val->remarks1;
switch ($favcolor) {
case "REFUND":
case "STALE":
if(date("d-m-Y",strtotime($funding_dt)) >= date("d-m-Y",strtotime('31-01-2007')))
{
$this->db->where('id', $id);
$this->db->update($this->db_sdip, array(
'remarks1 ' => 'Rejected',
'amc_remark' => 'Check in FD'
));
}
if( (date("d-m-Y",strtotime($funding_dt)) >= date("d-m-Y",strtotime('01-05-2003'))) and (date("d-m-Y",strtotime($funding_dt)) <= date("d-m-Y",strtotime('31-01-2007'))))
{
if($remarks1 = '')
{
$this->db->where('id', $id);
$this->db->update($this->db_sdip, array(
'remarks1 ' => 'Approved',
'amc_remark' => 'Office Note Dated '.date('d-m-Y')
));
}else{
$this->db->where('id', $id);
$this->db->update($this->db_sdip, array(
'remarks1 ' => 'Rejected',
'amc_remark' => 'Wrong Funding Date'
));
}
}
break;
default:
echo "Invalid Input";
}
}
}
else
{
return NULL;
}
}

Related

Go to default case from another case in PHP

It is possible to go to default case from within some other case like this?
$a = 0;
$b = 4;
switch ($a) {
case 0:
if ($b == 5) {
echo "case 0";
break;
}
else
//go to default
case 1:
echo "case 1";
break;
default:
echo "default";
}
I tried to remove the else and was expecting that it would continue evaluating all following cases until default but it gets into case 1 then. Why is it so and how can I get to the default one?
Yes you can if you reorder the case statements:
switch ($a) {
case 1:
echo "case 1";
break;
case 0:
if ($b == 5) {
echo "case 0";
break;
}
default:
echo "default";
}
Why is it so:
it is defined, if you de not have a break statement the next case will be executed. If there is no more case, the default will be executed if one is defined
You could re-order the case statements to allow a fall through to the next option, but if there are several times you wish to do this it can become impossible or just very fragile. The alternative is to just more the common code into a function...
function defaultCase() {
echo "default";
}
switch ($a) {
case 0:
if ($b == 5) {
echo "case 0";
}
else {
defaultCase();
}
break;
case 1:
echo "case 1";
break;
default:
defaultCase();
}
I would suggest using a simple if / else as I mentioned in the comments.
However, here's another way you could do it using a switch statement, if that helps:
switch ([$a, $b]) {
case [0, 5]:
echo 'case 0';
break;
case [1, $b]:
echo 'case 1';
break;
default:
echo 'default';
}

How to use switch in php

if (isset($_POST["submit"])){
$oride='';
$count = "25";
$origin = $_POST["origin"];
$destinataion = $_POST["destination"];
$oride = ($destination = $_POST["destination"] - $origin= $_POST["origin"]);
switch (true) {
case ($count<="0"):
echo "invalid";
break;
case ($count==="15"):
echo $count;
break;
case ($count==="16"):
$total = $count + "1";
echo $total;
break;
default:
echo "hello";
} }
The code will compute 1st then execute switch depending on what is the result of the computation. I tried if else but it will be too long because the case will go up to 130.
You must use the var $count in switch statement and the constant in case this way
switch ($count) {
case "0" :
echo "invalid";
break;
case "15":
echo $count;
break;
case "16":
$total = $count + "1";
echo $total;
break;
default:
echo "hello";
break;
}
You have to provide an expression to the switch statement, while the case statements are just "versions" of the result of that expression. The only thing you can NOT do directly is the "<= 0" expression, but you can work around it:
if (isset($_POST["submit"])){
$oride='';
$count = "25";
$origin = $_POST["origin"];
$destinataion = $_POST["destination"];
$oride = ($destination = $_POST["destination"] - $origin= $_POST["origin"]);
// --- normalize $count:
$count = $count <= 0 ? 0 : $count;
// use $count as expression:
switch ($count) {
case 0:
echo "invalid";
break;
case "15":
echo $count;
break;
case "16":
$total = $count + "1";
echo $total;
break;
default:
echo "hello";
} }

php switch between range of numbers does not work

I have this PHP function for changing color between 2 numbers:
function color_switch($number){
switch (true){
case $number == range(1 , 3):
$color = "progress-bar-danger";
break;
case $number == range(3 , 5):
$color = "progress-bar-warning";
break;
case $number == range(5 , 6):
$color = "progress-bar-default";
break;
case $number == range(6 , 8):
$color = "progress-bar-success";
break;
case $number == range(8, 10):
$color = "progress-bar-success";
break;
}
return $color;
}
But in action this function does not work for me. How should I fix this ?
You are comparing range() which is an array, and $number is integer, which is invalid,
Change your function something like,
function color_switch($number) {
switch ($number) { // switching the function argument
case $number <= 3 : // if less than three, execute case
$color = "progress-bar-danger";
break;
case $number <= 5 :
$color = "progress-bar-warning";
break;
case $number <= 6 :
$color = "progress-bar-default";
break;
case $number <= 8 :
$color = "progress-bar-success";
break;
case $number <= 10 :
$color = "progress-bar-success";
break;
}
return $color;
}
Your utilization of switch is incorrect and your utilization of range() is too.
Your parameter of switch should be the variable you evaluate.
Range() will return an array containing the range.
So the correct code is better :
function color_switch($number) {
switch ($number){
case in_array($number, range(1 , 3)):
$color = "progress-bar-danger";
break;
case in_array($number, range(3 , 5)):
$color = "progress-bar-warning";
break;
case in_array($number, range(5 , 6)):
$color = "progress-bar-default";
break;
case in_array($number, range(6 , 8)):
$color = "progress-bar-success";
break;
case in_array($number, range(8 , 10)):
$color = "progress-bar-success";
break;
}
return $color;
}

php's if shorthand when there are multiple elseifs

How can I use shorthand for php's if when there are multiple elseifs?
I know how to do it with one condition, but what when there are several?
This is how it is:
if($a == 00){
echo 'Clear';
}elseif ($a == 01) {
echo 'Processing';
} elseif ($a == 10) {
echo 'Marked for delete';
}
You can of course "chain" the ternary operator, but that results in horrible code. Don't do it.
Use an if/else, a switch or possibly an associative array as appropriate. For example, you could do this:
$messages = array(
00 => 'Clear',
01 => 'Processing',
10 => 'Marked for delete',
);
echo isset($messages[$a]) ? $messages[$a] : null;
In this case this won't be at all better than the if or switch statements, but it's a useful tool to keep in mind.
The switch statement?
switch ($a) {
case 0:
echo "Clear";
break;
case 1:
echo "Processing";
break;
case 2:
echo "Marked for delete";
break;
}
alternatively you can use the ternary operator:
echo ($a == 0 ? "Clear" :
($a == 1 ? "Processing" :
($a == 2 ? "Marked for delete" : "")));
use switch
switch ($a) {
case 1:
echo "clear";
break;
case 10:
echo "marked default";
break;
default:
echo "not tracked case";
break;
}
You should NEVER do this, it is utterly unreadable but...
echo ($a==00?"Clear":($a== 01?"Processing":($a == 10?"Marked For Delete":"")));
You can do it like that:
echo ($a==0 ? 'clear' : ($a==01 ? 'Processing' : ($a==10 ? 'Marked for delete' : '' )));
But Jon is right, don't do it - as you can see, the code is ugly.
I think the switch statement might be better suited for multiple elseif's
switch ($a) {
case "00":
break;
case "Clear":
break;
default:
break;
}
Here is example of ternary operator (shorthand of if/else)
$days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29
: ($year %400 ? 28 : 29)))
: (($month - 1) % 7 % 2 ? 30 : 31));
//returns days in the given month
But it will be confusing to work!
So i prefer to work with switch case!
switch ($type) {
case 'a':
$type = 'Type A';
break;
case 'b':
$type = 'Type B';
break;
case 'c':
$type = 'Type C';
break;
default:
break;
}

switch statement with two variables at a time

Could someone suggest the best way to have the following switch statement? I don't know that it's possible to compare two values at once, but this would be ideal:
switch($color,$size){
case "blue","small":
echo "blue and small";
break;
case "red","large";
echo "red and large";
break;
}
This could be comparable to:
if (($color == "blue") && ($size == "small")) {
echo "blue and small";
}
elseif (($color == "red") && ($size == "large")) {
echo "red and large";
}
Update
I realized that I'll need to be able to negate ($color !== "blue") and compare as opposed to equating variables to strings.
Using the new array syntax, this looks almost like what you want:
switch ([$color, $size]) {
case ['blue', 'small']:
echo 'blue and small';
break;
case ['red', 'large'];
echo 'red and large';
break;
}
You can change the order of the comparison, but this is still not ideal.
switch(true)
{
case ($color == 'blue' and $size == 'small'):
echo "blue and small";
break;
case ($color == 'red' and $size == 'large'):
echo "red and large";
break;
default:
echo 'nothing';
break;
}
Doesn't work. You could hack around it with some string concatentation:
switch($color . $size) {
case 'bluesmall': ...
case 'redlarge': ...
}
but that gets ugly pretty quick.
Found at http://www.siteduzero.com/forum/sujet/switch-a-plusieurs-variables-75351
<?php
$var1 = "variable1";
$var2 = "variable2";
$tableau = array($var1, $var2);
switch ($tableau){
case array("variable1", "variable2"):
echo "Le tableau correspond !";
break;
case array(NULL, NULL):
echo "Le tableau ne correspond pas.";
break;
}
?>
Your other option (though not pretty) is to nest the switch statements:
switch($color){
case "blue":
switch($size):
case "small":
//do something
break;
break;
}
var $var1 = "something";
var $var2 = "something_else";
switch($var1.$var2) {
case "somethingsomething_else":
...
break;
case "something...":
break;
case "......":
break;
}

Categories