PHP Shorten IF statement - php

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

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.

PHP if statements with multiple values

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

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

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){ ... }

Categories