PHP if else语句
我们有变量$country
,它可以给~50个不同的值。PHP if else语句
和变量$id
。
我们应该做的是给价值$id
对应$country
值,如:
if ($country = 'USA') { $id = 'usa_type'; }
else if ($country = 'France') { $id = 'france_type'; }
else if ($country = 'German') { $id = 'german_type'; }
else if ($country = 'Spain') { $id = 'spain_type'; }
...
...
...
else if ($country = 'Urugway') { $id = 'urugway_type'; }
else { $id = 'undefined'; }
else if
语句重复,每次和其他数据是典型的。
有没有办法缩短这段代码?
像:
[france]:'france_type;
[england]:'england_type;
...
[else]:'undefined'
感谢。
你可以只创建$id
从$country
:
$id = strtolower($country) . '_type';
如果您首先需要确定的$country
有效性,把你所有的国家放在一个数组中,然后用in_array
来确定i ˚F$country
是有效的:
$countries = array('USA', 'France', 'Germany', 'Spain', 'Uruguay');
if (in_array($country, $countries)) {
$id = strtolower($country) . '_type';
}
+1正是我即将回答的! – 2010-08-01 08:20:27
看起来很完美,谢谢你! – James 2010-08-01 08:24:56
看你的例子中,你可以做类似
$id = strtolower($country) + '_type';
将所有国家和代码在阵列像这样:
$countries = array("0" => array("country_name" => "usa",
"country_type" => "001") ,
"1" => array("country_name" => "uae",
"country_type" => "002"),
-----------------------------
-----------------------------
);
然后使用循环比较的国家名称,然后获得国家ID。
$country = "usa";
for($i = 0; $i < count($countries); $i++) {
if($country == $countries[$i]["country_name"]){
$id = $countries[$i]["country_type"];
break;
}
}
echo $id;
它看起来太重了。 – James 2010-08-01 08:29:06
,或者你可以创建一个数组
$country_to_id = array(
"USA" => "usa_type",
"Spain" => "spain_type_or_whatever",
....
);
$country_id = (array_key_exists($country,$country_to_id)) ? $country_to_id[$country] : 'undefined';
为什么这很重要?如果较短的代码难以理解,并且如此复杂,则有可能发生错误,因此有时需要更长的代码是值得的。 – James 2010-08-01 09:03:49