简体   繁体   English

PHP或声明||

[英]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 我有这么多的值,我需要与同一个变量进行比较,是否有更好的方法来更有效地编写,例如$city == -35 || -34 || -33 $city == -35 || -34 || -33 $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. $city == -35 || -34 || -33甚至更简单,这样我就不必重复变量名,因为它是相同的变量,只有值不断变化。

<?php

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

?>

Any suggestions? 有什么建议么?

You might use in_array() 你可以使用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))

Yes. 是。 Use in_array , 使用in_array

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

你可以使用:

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

Assuming that $xcity is a typo, 假设$xcity是拼写错误,

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

Use associative array. 使用关联数组。 in_array compare each element in array with your var. in_array将数组中的每个元素与var进行比较。 Associative array used hashtable. 关联数组使用哈希表。 It faster. 它更快。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM