Mas
Mas

Reputation: 127

PHP or statement ||

Use of || (or)

I got so many values which I need to compare with same variable, is there a better way to write more efficiently such as $city == -35 || -34 || -33 or even simpler so that I don't have to repeat variable name since it's the same variable only value keep changing.

<?php

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

?>

Any suggestions?

Upvotes: 3

Views: 7705

Answers (5)

Michael Berkowski
Michael Berkowski

Reputation: 270609

You might use in_array()

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

Or if they are consecutive ( I suspec they aren't and this is just an example)

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

Upvotes: 6

Vadim Baryshev
Vadim Baryshev

Reputation: 26189

Use associative array. in_array compare each element in array with your var. Associative array used hashtable. It faster.

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

Upvotes: 0

wallyk
wallyk

Reputation: 57774

Assuming that $xcity is a typo,

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

Upvotes: 1

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

You could use:

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

Upvotes: 1

mpen
mpen

Reputation: 282825

Yes. Use in_array,

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

Upvotes: 4

Related Questions