Multiple comparison operators for one variable? - php

I need to do multiple checks for a variable. I've seen an "Equals" example, here: w3schools.
But they are two different variables. Right now I have:
if ($color == 'blue')
{
//do something
}
But I need to to multiple checks for $color. Eg if it equals red or green too. How is this written?

As simple as:
if ($color == 'blue' || $color == 'red' || $color == 'green') {
//do something
}
There are several other options. Using switch operator:
switch ($color) {
case 'blue':
case 'red':
case 'green':
//do something
}
Or more complex using in_array function:
$colors = array('blue', 'red', 'green');
if (in_array($color, $colors)) {
//do something
}

Use a switch-statement.
switch($color)
{
case "blue":
// do blue stuff
break;
case "yellow":
// do yellow stuff
break;
case "red":
// do red stuff
break;
default:
// if everything else fails...
}
In case you want to do the same thing on all colors, just use the || (boolean or) operator.
if ($color == "blue" || $color == "red" || $color == "yellow")
{
// do stuff
}

You can also go with preg_match on this one. This might be overkill, but I'm sure it's very fast!
$color = "blue";
$pattern = "/^red|blue|yellow$/";
if ( preg_match($pattern,$color) ) {
// Do something nice here!
}

Related

Is there a more elegant way to execute this switch statement?

I have a large switch statement in my code, and I want it to do something like this:
// assign $foo
switch ($foo) {
case 1:
case 2:
// do X, then break if 1, do Y and break if 2
case 3:
case 4:
case 5:
// do A & B, break if 3, do C if 4 or 5, do D if 5 and then break
}
Such "groups" are prevalent throughout the switch statement and currently I just repeat the logic, keeping each case separate.
Am I wrong in assuming that this could be restructured into something that's objectively "better"?
Edit: I excluded my original code snippet from the question, since it had deeply flawed logic and didn't conform to the basic concepts of using a switch, replacing it with pseudocode that resembles the desired result.
As commented, that switch doesn't actually work as you think.
You're simply looking for:
if (in_array($foo, [1, 2])) {
...
if ($foo == 2) {
...
}
}
Alternatively:
switch ($foo) {
case 1:
case 2:
...
if ($foo == 2) {
...
}
break;
}
TLDR;
For simple "is it this", use a switch, if you need logical checks, use an if
The answer;
What you are asking is quite subjective, while using a switch for something simple is good, i.e;
<?php
$case = getCaseFrom("X"); // Let's say this = "a"
switch ($case)
{
case "a" : {
$thing = "a";
break;
}
case "b" : {
$thing = "b";
break;
}
case "c" : {
$thing = "c";
break;
}
default : {
$thing = "d";
}
}
?>
The same could be achieved by using;
<?php
$case = getCaseFrom("x");
$thing = $case;
// And even shorter;
$thing = getCaseFrom("x");
?>
Whereas, if you needed some logic to this...
<?php
$operator = getOperatorFrom("X"); // In this case, add
$num1 = 10;
$num2 = 2;
switch ($operator)
{
case "add" : {
$res = num1 + num2;
break;
}
case "subtract" : {
$res = num1 - num2;
break;
}
case "multiply" : {
$res = num1 * num2;
break;
}
case "divide" : {
$res = num1 / num2;
break;
}
}
?>
The alternative;
And of course, all of the above switches case be done using if else clauses, but a switch (IMO) is a neater, and more readable approach depending on what your certain criteria are (see the drawbacks).
The easiest way to look at it is;
If you need to check if something matches a value, use an if, if it is an enumerated set of values (let's say 1 to 4), a switch is subjectively better
The drawbacks;
A switch also doesn't let you have multiple "and" checks in the same statement, for example;
<?php
$case = getCaseFrom("X"); // In this case, a (does not have "b")
switch ($case)
{
case "a" :
case "b" : {
// This checks for a or b, not both, despite this not containing "b"
// this will still be accessed
break;
}
case "c" : {
// This will not be used as the break stops
// it from falling through to this clause
break;
}
}
if (stristr("a", $case) && stristr("b", $case))
{
// This checks to see if case contains a AND b
// therefore, this will not be used, as this
// does not have both a and b in $case
}
else if (stristr("a", $case) || stristr("b", $case))
{
// This checks to see if case contains a OR b
// therefore, this will be used, as this
// is checking that $case has "a" or "b" in it
// This is the same as the switch in this instance as it uses "or"
}
The noteworthy;
To be aware of the following also would be useful;
Inside a switches case, you cannot use login, for example;
case getThing("a") :
would cause an error
NB: Of course, when using the case statements, you don't need the curly braces added, they are mainly for code folding and ease of reading

Switch & Case multiple selections

I got an issue with switch.
Right now from my understanding it works like this:
if ( sizeof( $a ) !== sizeof( $types ) ) {
$type = $a[ 0 ];
switch ( $type ) {
case 'Red' :
$type = 'winered';
break;
case 'blue' :
$type = 'royalblue';
break;
case 'yellow' :
case 'lime' :
break;
case 'beige' :
$type = 'bright';
break;
default :
$type = get_option( 'my_option' );
break;
}
} else {
$type = get_option( 'my_option' );
}
So far so good. Whatever I select, it shows the case.
My issue is, it does it only one by one, I am able to select multiple cases like
case Red: case Blue:
$type = 'winered';
break;
But this won't work for me. In my scenario it is a checkbox I got case "Red" AND case "Blue" selected and want to display both "results": "winered" AND "royalblue". Right now it falls back to royalblue.
Any suggestions?
Thank you!
I dont think it is possible with a switch case to select multiple outcomes. I'd rather use an if statement something like:
if($type = 'red' || $type = 'blue'){
$type = 'winered';
$type = $type.'royalblue';
}
It doesn't really make sense why it would fall back to 'royalblue' other than:
'Red' != 'red', so it never really goes into the first case
Maybe this is how you have the types stored in $a, so that $a[0] is in fact 'blue', I would check that.
In any case, if you were interested in combination of different conditions, I would think that 'regular' if-then-else is the way to go. Case is generally faster, but offers itself for 'simpler' conditionals.
I hope this helps!
Your code is incomplete. However, I think the key is here:
$type = $a[ 0 ];
switch ( $type ) {
You only check the first value of $a. You can check all its values using a simple foreach:
// Put the selected values here; will join them at the end to get a string
$selected = array();
if (count($a) != count($types)) {
foreach ($a as $type) {
switch ($type) {
case 'Red':
$selected[] = 'winered';
break;
case 'blue':
$selected[] = 'royalblue';
break;
case 'yellow':
case 'lime':
// nothing here?!
break;
case 'beige':
$selected[] = 'bright';
break;
default:
$selected[] = get_option('my_option');
break;
}
}
} else {
$selected[] = get_option('my_option');
}
// Join the selected type with spaces
$type = implode(' ', $selected);

Can't get array_push working

I want to add values to an array so the output will be like this (1,2,3,4,5).
To accomplish this i tried to use array_push. I've tried a lot to get this working but it just outputs the last number which in this case is '5'. Do you guys see what is wrong with my code? Thanks in advance!
$websites = array();
case 'Hengelsport':
if ($waarde == 'true') {
array_push($websites,1);}
break;
case 'Diervoeders':
if ($waarde == 'true') {
array_push($websites,2);}
break;
case 'Vijverconcurrent':
if ($waarde == 'true') {
array_push($websites,3);}
break;
case 'Broqx':
if ($waarde == 'true') {
array_push($websites,4);}
break;
case 'Dekrabpaal':
if ($waarde == 'true') {
array_push($websites,5);}
break;
$this->articleData['website_ids'] = $websites;
You can't to have other value that last number, if you juste set $websites variable, like this : $websites = array();
And don't forget switch operator.
switch ($i) {
case "Hengelsport":
echo "i égal 0";
if ($waarde == 'true') {
array_push($websites,1);
}
break;
//...
}
Is it full code that you show us ?
Or for an easy way :
$website_ids = array(
'Hengelsport' => 1,
'Diervoeders' => 2,
'Vijverconcurrent' => 3,
'Broqx' => 4,
'Dekrabpaal' => 5
);
if ($waarde == 'true')
{
array_push($websites, $website_ids[$your_var_containing_name]);
}

Best way to check what a variable is

I was wondering what the quickest way would be to do something like the following:
if ($var == 1) {
// 1
}
if ($var == 2) {
// 2
}
if ($var == 3) {
// 3
}
etc, but then at the end having something like:
if ($var != 1 or 2 or 3) {
//Not a number
}
I was thinking about having an if(in_array(...)) statement at the end, but wanted to know your thoughts.
I would do this with a switch
switch ($var) {
case 0:
echo "var equals 0";
break;
case 1:
echo "var equals 1";
break;
case 2:
echo "var equals 2";
break;
default:
echo "var is not 0 1 or 2"
}
Also if you miss out a break statement then you can easily do a case when $var == 1 || $var == 2, read more
If all you want to know is whether "$var" is in your set {1, 2, 3}, then in_array is fine.
Otherwise, if you want to know which (if any) value you've got, then I'd do this:
if ($var == 1) {
// 1
}
else if ($var == 2) {
// 2
}
else if ($var == 3) {
// 3
}
else {
}
Note the "else if" to save you from re-checking what you already know.
Note, too, that PHP 4 and 5 also have a "switch" case/block:
switch ($i) {
case 1:
// 1
break;
case 2:
// 2
break;
case 3:
// 3
break;
default:
...
}
Or use a switch case, this better to read for much cases:
switch($var) {
case 1: /*1*/ break;
case 2: /*2*/ break;
case 3: /*3*/ break;
default: /*not 1 not 2 not 3*/
}
Use if/else if/else, with which you can decide whether strict or loose comparisons are appropriate.
With switch, it's always loose comparisons, which is why I prefer the if statement, since it makes it explicit what mode has been chosen.
if ($var === 1) {
// 1
}
else if ($var === 2) {
// 2
}
else if ($var === 3) {
// 3
}
else {
//neither 1, 2 nor 3
}

if statement formatting

Basically, I always use words 'and' & 'or' so, my scripts look like:
if ($value == '1' or $value == '2' or $value == '3') {
//do stuff
}
if ($value == '1' and $user_logged == 'Admin') {
//do stuff
}
It's possible get rid of of $value repeating?
Any benefit in using and and or instead of || and && ?
There is no way to shortcut expressions like
if ($value == 1 or 2 or 3) // invalid
But you can check the values in another way:
if (in_array($value, array(1, 2, 3))) {
// do stuff
}
The difference between or and || is operator precedence. Use || and &&, not or and and.
Answer 1.
$inArray = (1,2,3);
if (in_array($value,$inArray)) {
// do stuff
}
Answer 2.
Operator precedence
You can use first if as a switch statement:
switch($value) {
case "1":
echo "value is 1";
break;
case "2":
echo "value is 2";
break;
case "3":
echo "value is 3";
break;
}
Answer to your second question: Operator precedence

Categories