PHP or operator ||

Use ||

(or)

I have so many values ​​that I need to compare with the same variable, is there a better way to write more efficiently, for example, $city == -35 || -34 || -33

or even simpler, so that I don't have to repeat the name of the variable, since it has the same variable, only the value changes ...

<?php

if ($city == -35 || $city == -34 || $xcity == -33)
{
    $region = "noindex";
}

?>

      

Any suggestions?

+3


source to share


5 answers


you can use in_array()

if (in_array($city, array(-35, -34, -33))) {
  $region = "noindex";
}

      



Or, if they are consistent (I suspect they are not, and this is just an example)

in_array($city, range(-35, -33))

      

+6


source


Yes. Use in_array

,



in_array($city, array(-35,-34,-33))

      

+4


source


You can use:

if (in_array($city, array(-35, -34, -33))

      

+1


source


Assuming which $xcity

is a typo,

switch ($city)
{
case -35:
case -34:
case -33:
     $region = "noindex";
     break;
}

      

+1


source


Use an associative array. in_array compares each element in the array to your var. The associative array used a hash table. It's faster.

$cities = array(-33 => 1, -34 => 1, -35 => 1);
if (isset($cities[$city])) {
    $region = "noindex";
}

      

0


source







All Articles