php's if shorthand when there are multiple elseifs - php

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

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

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

php comparison operators 'is less than' (>) used in negative numbers is also including 0 in this switch statement?

This is the switch statement.
Only if the variable $thumbs_number is less than -1 (e.g. -2, -3, -4, etc.), the class bad should output.
But right now, the class bad is also being output when $thumbs_number is 0 (-1 and 1 have the right class: average).
<div class="topic-like-count
<?php // Apply style based on number of votes
switch ($thumbs_number) {
case ($thumbs_number < -1): echo ' bad'; break;
case ($thumbs_number == 0):
case ($thumbs_number == 1): echo ' average'; break;
case ($thumbs_number == 2):
case ($thumbs_number == 3): echo ' good'; break;
case ($thumbs_number == 4):
case ($thumbs_number == 5): echo ' great'; break;
case ($thumbs_number == 6):
case ($thumbs_number == 7): echo ' excellent'; break;
case ($thumbs_number > 7): echo ' brilliant'; break;
}
?>
">
What is happening?
You a misusing the switch statement.
Each case statement compares the result of the expression to the value passed to switch. So here you are comparing $thumbs_number to the result of ($thumbs_number < -1), which is either true or false.
Do this instead:
switch ($thumbs_number) {
case 0:
case 1:
echo "average";
break;
case 2:
case 3:
echo "good";
break;
....
default:
if ($thumbs_number <= -1) echo "bad";
else if ($thumbs_number > 7) echo "brillant";
}
I faced a similar problem and I was reluctant to write a long if-else if block. Searching for an answer led me to this page.
With this technique, all you need to do is replacing
switch ($thumbs_number)
with
switch (true)
Here is my version of the code:

PHP switch case more than one value in the case

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

How to add multiple condition cases inside Switch method?

Is there a way to include multiple cases inside a switch method in php?
The switch statement works by evaluating each case expression in turn and comparing the result to the switch expression. If the two expressions are equivalent, the case block is executed (within the constraints established by break/continue constructs). You can use this fact to include arbitrary boolean expressions as case expressions. For example:
<?php
$i = 3;
$k = 'hello world';
switch (true) {
case 3 == $i and $k == 'hi there';
echo "first case is true\n";
break;
case 3 == $i and $k == 'hello world';
echo "second case is true\n";
break;
} //switch
?>
This outputs:
second case is true
I don't use this sort of construction very often (instead preferring to avoid such complex logic), but it sometimes comes up where a complicated if-then statement might otherwise be used, and can make such snippets much easier to read.
What's wrong with simply nesting switches?
$i = 1;
$j = 10;
switch($i) {
case 2:
echo "The value is 2";
break;
case 1:
switch($j) {
case 10:
echo "Exception Case";
break;
default:
echo "The value is 1";
break;
}
break;
default:
echo "Invalid";
break;
}
Yes it is possible
Here is an example to start with
<?
$i = 1;
$j = 10;
switch($i) {
case "2":
echo "The value is 2";
break;
case ($i==1 && $j==10):
echo "Your exceptional Switch case is triggered";
break;
default:
echo "Invalid";
break;
}
?>

Categories