Home >Backend Development >PHP Tutorial >PHP三元运算的2种写法代码实例_php实例

PHP三元运算的2种写法代码实例_php实例

WBOY
WBOYOriginal
2016-06-07 17:19:41817browse


首先,我们现在看一个简单的例子:

复制代码 代码如下:
$a = 2;
($a == 1) ? $test = "企业" : $test = "地区";#写法一
echo $test;
?>

上述例子呢,先判断$a是否为1 如果是 将“企业”这个字符串存入$test变量里然后输出,如果不是 将“地区”这个字符串存入$test变量里然后输出;
上诉例子代码等价于:
复制代码 代码如下:
$a = 2;

#写法二
$test = ($a == 1) ? "企业" : "地区";

#写法三
if($a == 1){
   $test="企业";
}else{
   $test="地区";
}
echo $test;

?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn