PHP if statements with multiple values - php

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()

Related

php shorthand for or statement [duplicate]

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.

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.

In php how do you say if ($x == 1 or 2 or 3 or 4) {do function} without repeating code many times?

Im not great in php and I could do with a little help. I want to say something like
if ($x == 1 or 2 or 3 or 4) {do function}
but the only way i know how to do that is to go
if (($x == '1') or ($x == '2')) or...
which seems a long way of doing it. Is there a better way I am missing, like
if ($x == 1,2,3,4) {do}
Thanks for your answers!
you can use in_array function
$array = array(1,2,3,4)
if(in_array($x, $array)) {
// do something
}
switch ($x) {
case 1:
case 2:
case 3:
case 4:
// do
break;
}
Or you can use the in_array() function creating an array such as $a = array(1,2,3,4); and then do if (in_array($x, $a)).
If you are concerned about space, you can also use the shortcut:
if (in_array($x, array(1,2,3,4))) { /* do */ }
You can create an array of expected values and then use function in_array().
http://php.net/manual/en/function.in-array.php
If it's a range, you could do:
if ($x >= 1 && $x <= 4) { }
You could also construct an array and check if the number is in that array.
<?php
$data = array(1,2,3,4);
if(in_array($x, $data)){
// execute function
}
?>
All the above ideas are good. I am going to show another way, that is not better, but is different.
You can store comparations in variables, to use later or combine. This helps readability, and make complex expresions easy to create and read. It obviusly remove any repetition.
$is_number = ($str=="one" or $str=="two" or $str=="tree");
$is_english = ($str=="one" or $str=="horse");
$is_french = ($str=="baguette" or $str=="amie");
$is_fun = $is_french or $is_english;
if($is_french and !$is_number){ ... }

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

How do I add an OR function to a PHP code?

Firstly, dont laugh, I know it is basic.
I have this code: if ($pageid == '9') { echo... and I want to add an OR to it, so I tried: if ($pageid == '9' or '5') { echo... but it didnt work. How do I add an OR function to this?
if ($pageid == '9' || $pageid == '5') { echo...
Note that if you have a large number of pageids to check for some reason, you can utilize arrays:
if(in_array($pageid, array(9, 5, 3, 12, 5)) { echo ...
or works instead of || also but || is more commonly used.
Just to mention another approach that makes use of PHP's in_array - it's quite handy if you've a few values you want to treat as a cluster that don't justify a switch but would be painfully verbose to use a traditional or for.
if(in_array($pageID, array(1, 2, 3))) {
// Do exciting things...
}
if ($pageid == '9' || $pageid == '5')
this should work too. i am not sure why this won't work in your case
if($pageid == "9" OR $pageid == "5"){
echo "pageid ".$pageid;
}
for more information see this http://php.net/manual/en/language.operators.logical.php
switch ($pageid) {
case '5':
case '9':
echo "...";
break;
default:
// Do something useful
break;
}
This is useful, if you have more than one cases, because it prevents you from ugly "elseif"-chains. Also if you have one case with many different values its more readable and its easy to add additional values. You just need to add a new case 'xy': line.

Categories