Simpler way for multiple 'or' statements with a single variable - php

I have the following if statement (except the final one would be much longer with more values) that I would like to condense.
if ($row['titleId'] == '123' || $row['titleId'] == '456' || $row[){
I would imagine it would end up something like:
if ($row['titleId'] == ('123'||'456'){}
Or would I be better off like this:
$array = ('123','456')
if (in_array($row['titleId'], $array){}

You can use switch for this:
switch ($row['titleId']) {
case '123': case '456': case '789': case '314': case '271':
doSomething();
}
I'd probably still prefer to have each case on a separate line but, if your goal is to reduce the "height" of your code, you can do it as above.
In terms of shortening the code in your comment, which apparently looks like this:
switch($row['titleId']){
case '8216': case '8678': case '8705': case '8216': case '8707':
$rows[$row['titleId']]=array();
break;
case '8214':
$rows['8216'][]=$row['titleId'];
break;
case '8791':
$rows['8678'][]=$row['titleId'];
break;
case '8643':
$rows['8705'][]=$row['titleId'];
break;
case '8666':
$rows['8707'][]=$row['titleId'];
break;
}
you could opt for something like:
$xlat = array('8214'=>'8216', '8791'=>'8678', '8643'=>'8705', '8666'=>'8707');
switch($row['titleId']){
case '8216': case '8678': case '8705': case '8216': case '8707':
$rows[$row['titleId']]=array(); break;
default:
if (array_key_exists($row['titleId'],$xlat)) {
$rows[$xlat[$row['titleId']]][]=$row['titleId'];
}
}
This compresses the common cases by putting them under the control of an associative array. Basically, if the title ID is in the array as a key, its lookup value will be used to affect the correct $rows entry.

Related

A better PHP switch command

In pick basic there is a case command which functions similar to the switch command basically doing nested if then else commands. The code is like this:
begin case
case a=4;do something
case b=5 or c=6;do something
case y=x and f=z;do something
case 1;do something
end case
if any of the conditions are true, it falls into that case. I know PHP has the switch command, but that is limited to the value of one variable. Is there a way to code the above in PHP or javascript for that matter without a bunch of if then else commands similar to the above?
If you really don't want to use if/else, then switch (true) can work:
switch (true) {
case ($a === 4):
doSomething();
break;
case ($b === 5 || $c === 6):
doSomething();
break;
case ($y === $x || $f === $z):
doSomething();
break;
default:
break;
}
However, it is less typing, and it makes your code more readable, if you simply use if/else instead, just as Shomz suggested. I really wouldn't recommend using switch (true).
Replacing case with else if is only 3 bytes longer, I don't see the big deal because that is exactly what the if/else is for. Switches are used for single variables, as you said.
Your do something could also include a result variable or a flag that will be set if any of the conditions are met.
So this:
begin case
case a=4;do something
case b=5 or c=6;do something
case y=x and f=z;do something
case 1;do something
end case
could be:
var case = false;
if (a==4) {dosomething(); case = true}
else if (b==5 || c==6) {dosomething(); case = true}
else if (y==z || f==z) {dosomething(); case = true}
else if (1) {dosomething(); case = true} // supposedly the default case?

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 same value in multiple cases

I really like the structure of the switch statement compared to using multiple if else.
However some times I want to use the switch statement and have the same value in multiple cases. Can this be done somehow?
switch($fruit) {
case 'apple':
case 'orange':
// do something for both apples and oranges
break;
case: 'apple':
// do something for only apples
break;
case: 'orange':
// do something for only oranges
break;
}
I hope my example show what I intend to do...
No, it cannot. The first case that matches and everything following it until the first break statement or the end of the switch statement will be executed. If you break, you break out of the switch statement and cannot re-enter it. The best you could do is:
switch ($fruit) {
case 'apple':
case 'orange':
...
switch ($fruit) {
case 'apple':
...
case 'orange':
...
}
}
But really, don't. If you need some special action for those two before the individual switch, do an if (in_array($fruit, ['apple', 'orange'])) ... before the switch. Or rethink your entire program logic and structure to begin with.
Create some function and do it like this:
switch($fruit) {
case: 'apple':
apple_and_orange_function();
apple_function();
break;
case: 'orange':
apple_and_orange_function();
orange_function();
break;
}
You cannot match something multiple times, but you can write cascades like these:
switch($fruit) {
case 'apple':
// do something for only apples
case 'orange':
// do something for both apples and oranges
break;
case: 'grapefruit':
// do something for only grapefruits
break;
}
What you want can only be performed with if-else's or deceze's solution though

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

Switching a conditional case in php

I use javascript to send cases to and ajax function. The cases are taken from the link id. For example, if user clicked this link:
<a id="answer-yes-123">click this</a>
The javascript will split the id to 3 part, and send the middle part "yes" to ajax as a case. For most cases, when ajax receives the case, if yes do this if no do that.
switch ($case) {
case 'yes' :
$assignment->add();
break;
case 'no' :
$assignment->remove();
break;
There's one exception-- a numerical case. If the middle part of the link is a number, I don't know how to make the switching statement. There are potentially unlimited different numbers, I can't make each of them a case, How to make a condition like if(is_int($case)) to work as a case?
In the switch default: case, you can test is_int():
switch ($case) {
case 'yes' :
$assignment->add();
break;
case 'no' :
$assignment->remove();
break;
default:
// Determine the numeric value however you need to
// is_int(), is_numeric(), preg_match(), whatever...
if (is_int($case)) {
// numeric stuff
}
}
This is a little strange logically, because default: is typically used for the do this if nothing else is met condition. In your case though, if you don't need to further divide the numeric case much it works. Just be sure to comment it clearly in your code so you remember why you did it when you look back on it in six months.
Update after comments:
Since you already used the default:, I believe you can actually use an expression inside a case. This warrants even clearer commenting since it is not a common practice and goes kind of against the purpose of a switch:
switch ($case) {
case 'yes' :
$assignment->add();
break;
case 'no' :
$assignment->remove();
break;
// This actually works, but is highly weird.
// One of those things I can't believe PHP allows.
// is_int(), is_numeric(), preg_match(), whatever...
case is_int($case):
// Numeric stuff
break;
default:
// default stuff
}
Write the if-statement around the switch.
Something like this comes to my mind:
if (is_int($case)) {
// ...
} else {
switch ($case) {
// ...
}
}
Michael Berkowski's answer is perfect, but if don't want to use default case like this that could work also:
switch (preg_replace('/^[0-9]*$/','numeric',$case)) {
case 'yes' :
$assignment->add();
break;
case 'no' :
$assignment->remove();
break;
case 'numeric' :
$assignment->remove();
break;
default:
//...
break;
}
Use PHP's is_numeric
http://php.net/manual/en/function.is-numeric.php
if (is_numeric($case)) {
// ...
} else {
switch ($case) {
// ...
}
}

Categories