php shorthand for or statement [duplicate] - php

Basically what I'm wondering if there is a way to shorten something like this:
if ($variable == "one" || $variable == "two" || $variable == "three")
in such a way that the variable can be tested against or compared with multiple values without repeating the variable and operator every time.
For example, something along the lines of this might help:
if ($variable == "one" or "two" or "three")
or anything that results in less typing.

in_array() is what I use
if (in_array($variable, array('one','two','three'))) {

Without the need of constructing an array:
if (strstr('onetwothree', $variable))
//or case-insensitive => stristr
Of course, technically, this will return true if variable is twothr, so adding "delimiters" might be handy:
if (stristr('one/two/three', $variable))//or comma's or somehting else

$variable = 'one';
// ofc you could put the whole list in the in_array()
$list = ['one','two','three'];
if(in_array($variable,$list)){
echo "yep";
} else {
echo "nope";
}

With switch case
switch($variable){
case 'one': case 'two': case 'three':
//do something amazing here
break;
default:
//throw new Exception("You are not worth it");
break;
}

Using preg_grep could be shorter and more flexible than using in_array:
if (preg_grep("/(one|two|three)/i", array($variable))) {
// ...
}
Because the optional i pattern modifier (insensitive) can match both upper and lower case letters.

Related

In PHP, is there a short way to compare a variable to multiple values?

Basically what I'm wondering if there is a way to shorten something like this:
if ($variable == "one" || $variable == "two" || $variable == "three")
in such a way that the variable can be tested against or compared with multiple values without repeating the variable and operator every time.
For example, something along the lines of this might help:
if ($variable == "one" or "two" or "three")
or anything that results in less typing.
in_array() is what I use
if (in_array($variable, array('one','two','three'))) {
Without the need of constructing an array:
if (strstr('onetwothree', $variable))
//or case-insensitive => stristr
Of course, technically, this will return true if variable is twothr, so adding "delimiters" might be handy:
if (stristr('one/two/three', $variable))//or comma's or somehting else
$variable = 'one';
// ofc you could put the whole list in the in_array()
$list = ['one','two','three'];
if(in_array($variable,$list)){
echo "yep";
} else {
echo "nope";
}
With switch case
switch($variable){
case 'one': case 'two': case 'three':
//do something amazing here
break;
default:
//throw new Exception("You are not worth it");
break;
}
Using preg_grep could be shorter and more flexible than using in_array:
if (preg_grep("/(one|two|three)/i", array($variable))) {
// ...
}
Because the optional i pattern modifier (insensitive) can match both upper and lower case letters.

Short if statement

I have found something weird...,
I have this piece of code at the end of my function:
return $class == 3?"red":$class==2?"orange":$class==1?"yellow":"";
Now, when $class == 2 this returns "yellow" and not "orange" like I expected.
Can someone explain this to me?
You need to use parentheses as ternary operators are left-associative in PHP. Associativity is how "operators of the same precedence are grouped in the absence of parentheses" - from Operator Associativity
$class == 3?"red":($class ==2?"orange":($class ==1?"yellow":""));
This is because it is treated like it was:
return (($class == 3?"red":$class==2)?"orange":$class==1)?"yellow":"";
So add brackets to force the right use:
return $class == 3?"red":($class==2?"orange":($class==1?"yellow":""));
I would never code it like that. I believe that when you are coding, you really want to see immediately what a piece of code is doing. This won't do that, this is just giving you headaches ;-)
Maybe change it to something clear:
switch($class) {
case 1:
return 'yellow';
case 2:
return 'orange';
case 3:
return 'red';
default:
return '';
}
use parentheses:
$class = 2;
echo $class == 3?"red":($class==2?"orange":($class==1?"yellow":""));
Output : orange

Checking one variable against multiple values?

Currently, I'm doing something like this:
if ( in_array ( $variable, ["a","b","c"] ) ) { ... }
Which reads a little easier than
if ( $variable == "a" || $variable == "b" || $variable == "c" ) { ... }
But I was wondering, are there more efficient ways, instead of checking a value in an array?
Try like this
$my_array = array_flip(array('a', 'b', 'c', 'd', ...));
if (isset($my_array[$variable])) ...
This has one-time O(n) cost to create $my_array, then checking for a match is O(1).
You can use switch case statement for checking variable against multiple values.
Please refer the code snippet mentioned below
e.g.
switch($a)
{
case 'a':
//do something
break;
case 'b':
//do something
break;
case 'c':
//do something
break;
}

PHP Shorten IF statement

So I have a variable we will say $string = 2;
if i want to check that variable for either 2 conditions I'd typically do
if($string == 2 || $string == "Hello world"):
Is there anyway to combine these two args into something shorter like
if($string(==2 || =="hello world")):
I've googled this but I cant come up with the right phrase to get back the answer I'm looking for so explaining it at this point is the easiest.
if (in_array($string, array(2, 'Hello world')))
See http://php.net/in_array.
A sick part of me wanted to answer this.
function f($a){
$args = func_get_args();
return in_array($a, array_slice($args, 1));
}
used like
if(f($str, 1, "hello world", 3, "etc")){
}
If variable have many states that can be processed in different ways, you can use switch statement:
switch($var)
{
case 1:
case 2:
//some action
break;
case 3:
break;
}

PHP make if shorter

What is a true way to write like:
if ($variable == '(value1/value2/value3)' ) { }
It should work similar to:
if ($variable == 'value1' || $variable == 'value2' || $variable == 'value3') { }
Just want to make this code shorter (now I use switch).
Thanks.
Try in_array():
if (in_array($variable, array('value1', 'value2', 'value3'))) {}
If you do happen to have a group of values separated by, in your example, a /, just explode() it and you'll have an array to plug into in_array():
if (in_array($variable, explode('/', 'value1/value2/value3'))) {}
It might seem like you could just use strpos() instead since it's a long string of values, but that's not how one would work with a delimited string of multiple values (use explode() instead, as above):
if (strpos('value1/value2/value3', $variable) !== false) {}
Also shorter:
if (preg_match('#^(?:value1|value2|value3)$#', $variable) {
Not that it's necessarily the best way to do it. The long way, using just if and || statements, is going to be simple to read even though it's lengthy, and will be the most efficient to run.
switch ($variable)
{
case "value1":
case "value2":
case "value3":
...
break;
default: // else
...
}

Categories