加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP if else语句

发布时间:2020-12-13 22:07:37 所属栏目:PHP教程 来源:网络整理
导读:我们有变量$country,它可以提供~50个不同的值. 并且变量$id. 我们应该做的是为$country值赋予$id的值,例如: if ($country = 'USA') { $id = 'usa_type'; }else if ($country = 'France') { $id = 'france_type'; }else if ($country = 'German') { $id = 'g
我们有变量$country,它可以提供~50个不同的值.

并且变量$id.

我们应该做的是为$country值赋予$id的值,例如:

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'; }

否则if语句每次都重复,其他数据是典型的.

有没有办法缩短这段代码?

喜欢:

[france]:'france_type;
[england]:'england_type;
...
[else]:'undefined'

谢谢.

解决方法

你可以从$country创建$id:

$id = strtolower($country) . '_type';

如果您首先需要确定$country的有效性,请将所有国家/地区放入数组中,然后使用in_array确定$country是否有效:

$countries = array('USA','France','Germany','Spain','Uruguay');
if (in_array($country,$countries)) {
    $id = strtolower($country) . '_type';
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读