Charas
Charas

Reputation: 1827

How to simplify PHP logical operator?

I have searched and read the documentation and experimented on these logical operator however seem like nothing works. I want to simplify my if statement so that if variable is the same I don't need to keep rewriting it. For example:

<?php
if($var_1 == 'val_1' || $var_1 == 'val_2' || $var_1 == 'val_3' || $var_2 == 'val_4' || $var_2 == 'val_2' || $var_3 == 'val_5') {
    // Do something
} else {
    ....
}
?>

I want to simplify it to be something like this:

<?php
if($var_1 == ('val_1' || 'val_2' || 'val_3') || $var_2 == ('val_4' || 'val_2') || $var_3 == 'val_5') {
    // Do something..
}
?>

However the code above does not work, so rather than writing $var_1 over and over for each different value, how do I write it once ? I am strictly looking for answers using IF statement, not SWITCH or any other statement, I know I can use switch for this case, but I am specifically looking for the logical operator.

Thank you in advance.

Upvotes: 0

Views: 103

Answers (3)

Pavlo Zhukov
Pavlo Zhukov

Reputation: 3337

I do like this:

<?php
if(in_array($var_1, array('val_1', 'val_2', 'val_3')) || in_array($var_2, array('val_4', 'val_2')) || $var_3 == 'val_5') {
    // Do something..
}
?>

See in_array()

Upvotes: 2

Marin N.
Marin N.

Reputation: 366

You can use the in_array() function. More on the subject: http://php.net/manual/en/function.in-array.php . E.g.

<?php
//Define your arrays or get them from some query.. etc
$array1 = array("val_1", "val_2", "val_3");
$array2 = array("val_4, val_2");
$array5 = array("val_5");

//Check if variables are in the defined arrays
if (in_array("var_1", $array1) || in_array("var_2", $array2) || in_array("var_3", $array3)) {
//Do something

}

?>

Upvotes: 0

Ashil John
Ashil John

Reputation: 7762

You could use the in_array() function for this.

in_array — Checks if a value exists in an array

<?php

$var_1_array = array('val_1', 'val_2', 'val_3');
$var_2_array = array('val_2', 'val_4');
$var_3_array = array('val_5', 'val_6');

if(in_array($var_1, $var_1_array) || in_array($var_2, $var_2_array) || in_array($var_3, $var_3_array)) {
    // Do something..
}

?>

Upvotes: 0

Related Questions