Home > php教程 > php手册 > body text

php 三元运算符的使用介绍,php运算符

WBOY
Release: 2016-06-13 08:45:37
Original
1220 people have browsed it

php 三元运算符的使用介绍,php运算符

我们写PHP的时候,可能if{...}else{...}用的是最多的,但是有时候,我们可以用C里边的三元运算,可以使代码精减很多!本文章讲述我在php开发中使用三元运算的一些技巧和需要注意的地方。需要的码农可以参考一下。

 

今天一个网友在群里发了个题目不难,但是可能会错 

<span>echo</span> 
<span>$a</span> == 1 ? 'one' : 
<span>$a</span> == 2 ? 'two' : 
<span>$a</span> == 3 ? 'three' : 
<span>$a</span> == 4 ? 'foura' : 'other'<span>; 
</span><span>echo</span> "\n"; 
Copy after login

输出结果是:


 

结果是:four 

 

一开始想不明白,按照我的理解,应该是这样的逻辑: 
echo ($a == 1 ? 'one' : 
( $a == 2 ? 'two' : 
( $a == 3 ? 'three' : 
($a == 4 ? 'four' : 'other')))); 
输出为:two 

 

后来在kevinG(qq:48474)的指教下,参看php手册,终于明白了php的三元符的解释是从左到右的, 

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template