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;
}
Related
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.
Is there a shorter way of writing this?
<?
if($_GET['id']==1 ||
$_GET['id']==3 ||
$_GET['id']==4 ||
$_GET['id']==5)
{echo 'does it really have to be this explicit?'};
?>
Something like this perhaps?
<?
if($_GET['id']==1 || 3 || 4 || 5){echo 'this is much shorter'};
?>
Just try with:
if ( in_array($_GET['id'], array(1, 3, 4, 5)) ) {}
Maybe not shorter but more readable. Try the in_array() function:
if (in_array($_GET['id'], array(1, 3, 4, 5)))
{
echo "What about this?";
}
Perhaps switch may help
switch($_GET['id']) {
case 1:
case 3:
case 4:
case 5:
echo 'Slect maybe :P';
break;
}
You can use regular expression like below:
preg_match(['1-4']);
Declare an array:
$values = array(1,3,4,5);
Get your variable
$id = $_GET['id'];
Now use PHP in_array();
if(in_array($id, $values)){
//do something
}
Read about in_array()
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.
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;
}
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
...
}