A simpler way to write an if statement with multiple values - php

if(($x == "m") || ($x == "k") || ($x == "y") || ($x == "p") || ($x == "z"))
I'm sure there is a better approach to this. It isn't ideal to be repeating $x multiple times. Is there a better and more simpler way to write the above statement?
EDIT:
if($x == ('m' || 'k' || 'y' || 'p')
Something like the above perhaps?

You could use in_array like so:
if( in_array($x, Array("m","k","y","p","z")))
Or you could build a string and test it:
if( strpos("mkypz",$x) !== false)
Or with regex:
if( preg_match("/[mkypz]/",$x))
Or with a switch:
switch($x) {
case "m":
case "k":
case "y":
case "p":
case "z":
// do something
break;
}
The last two probably aren't a good idea, but it depends on exactly what you're doing, where $x is coming from, etc.. I just wanted to illustrate that there are many ways to do this.

You could build an array of values and use in_array().
$check = array('11','23','44')
if(!in_array($x, $check)){
.... do stuff
}
or do a switch
switch($x){
case "11":
case "23":
case "44":
echo "match:" break;
default:
echo "no match"; break;
}
The possiblilities are endless....

use in_array() , bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

You can use the in_array() function.
From the php documentation site.
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>
PHP documentation

You could use strpos:
if ( strpos( "mkyxpz" , $x) !== false )

Maybe, instead of if, consider switch:
switch($x) {
case 'm':
case 'k':
case 'y':
case 'p':
case 'z':
[statements];
break;
default:
[more statements];
break;
}
Notice that the value of $x will "fall through" every case condition until it reaches a break statement.

Related

PHP - Switch case evaluates to true while the same statement in if doesnt

I don't quite understands this.. Take a look at the following:
$value = 0;
if($value >= 90) {
// this does not return true
}
switch($value) {
case $value >= 90:
// this however does
break;
}
Am i missing something very obvious ?
$value >= 90 evaluates to false
As $value is 0, it is considered false. That's why your case works.
In a simple way it can be rewritten as:
switch($value) {
case false:
// this works
break;
}

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

Case statement is not outputting correctly?

This is very strange but below is my case statement:
switch($grade){
case ($average >70):
$grade = 'A';
break;
case ($average >=60 && $average <=69):
$grade = 'B';
break;
case ($average >=50 && $average <=59):
$grade = 'C';
break;
};
So if its 70+ it is grade A, 60-69 grade B, 50-59 grade C.
But instead it outputting this: 60+ grade A, 50-59 grade B, 40-49 grade C.
Why is it doing this because function seems correct?
echo "<p><strong>Average Mark:</strong> $average</p>";
echo "<p><strong>Average Grade:</strong> $grade</p>";
As others mentioned in comments, the "condition" in a case should be a static value, not a logical expression.
Also, the value you're switching on (in your case, $grade) should is the one you're testing. You appear to be using it as a hint about what variable you're assigning.
The simplest way to fix your code would be to use an if-elseif-else construct:
if ($average >70)
$grade = 'A';
elseif ($average >=60 && $average <=69)
$grade = 'B';
elseif ($average >=50 && $average <=59)
$grade = 'C';
However, to be perverse, and to illustrate how a switch statement works, you could also do the following:
switch(true){
case ($average >70):
$grade = 'A';
break;
case ($average >=60 && $average <=69):
$grade = 'B';
break;
case ($average >=50 && $average <=59):
$grade = 'C';
break;
};
In this example I'm comparing the value true to each of the cases in turn, where each of those case-values is actually the result of evaluating a boolean expression. The first expression whose value matches true will fire.
Probably not much help, if you don't understand switch statements.
Edit: I just noticed that there's a gap in the logic: what if someone's average is exactly 70? Using a cascading statement like a switch or if-else, you can eliminate some of the redundant (and in this case damaging) code, thus:
if ($average >=70)
$grade = 'A';
elseif ($average >=60)
$grade = 'B';
elseif ($average >=50)
$grade = 'C';
// ...
else
$grade = 'F';
...and so on, to whatever lowest grade you're using.
For those of you saying switch the variable you $average, you are wrong. The only reason it is evaluating in that instance is because switch uses loose comparison, so it is saying that $average being set is true and comparing it to the conditionals, all of which will be either true or false. Previously, using $grade which was unset was evaluating the switch to false because in loose comparison, a variable which is unset will throw a notice and return false.
While I recommend using if-then-else, the proper answer for using a switch statement in this case is as follows:
switch (true) {
case ($average >= 70):
$grade = 'A';
break;
case ($average >= 60 && $average < 70):
$grade = 'B';
break;
case ($average >= 50 && $average < 60):
$grade = 'C';
break;
}
Like said above, every statement will return either true or false. The idea is that only one statement should ever return true at one time, thus the switch statement will match it's value of true to the one statement that passed and execute that code only, since all of the other ones are false and didn't match.
You should use if/else - statements:
if($average >70)
{
$grade = 'A';
} else if($average >=60 && $average <=69)
{
$grade = 'B';
} else if($average >=50 && $average <=59)
{
$grade = 'C';
}
Edit: Alternatively you can calculate the $grade value (50-100 in this example):
$grades = "CBAAA";
$grade = $grades[(int)($average/10) - 5];
The switch loop compares the cases. If you really want to use switch for the job (and not if / elseif / else), then you can to it with a switch that compares against TRUE:
switch(TRUE)
{
case $average > 70:
$grade = 'A';
break;
case $average >= 60 && $average <= 69:
$grade = 'B';
break;
case $average >= 50 && $average <= 59:
$grade = 'C';
break;
default:
throw new Exception(sprintf('Unable to map average (%d) to a grade.', $average));
}

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