Heim  >  Artikel  >  php教程  >  php 三元运算符的使用介绍,php运算符

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

WBOY
WBOYOriginal
2016-06-13 08:45:371159Durchsuche

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"; 

输出结果是:


 

结果是:four 

 

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

 

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn