Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将php语句的某些行转换为三元运算符_Php_Ternary Operator - Fatal编程技术网

将php语句的某些行转换为三元运算符

将php语句的某些行转换为三元运算符,php,ternary-operator,Php,Ternary Operator,这是我第一次学习三元运算符。我在这里要做的是将php语句的一些行转换成三元运算符。有人能帮我检查一下我在这里做的事情是否正确吗。以及如何回应它。谢谢 <?php $tmp = 'this.ppt'; $tail = array_pop(explode('.',$tmp)); //'{file}' $allow = array('ppt','pdf','docx'); if (in_array($tail, $allow) {

这是我第一次学习三元运算符。我在这里要做的是将php语句的一些行转换成三元运算符。有人能帮我检查一下我在这里做的事情是否正确吗。以及如何回应它。谢谢

 <?php
      $tmp = 'this.ppt';
      $tail = array_pop(explode('.',$tmp)); //'{file}'
      $allow = array('ppt','pdf','docx');
         if (in_array($tail, $allow) {
             $type = $tail;
         } 
         elseif ($tail == 'doc') {
             $type = 'docx';
         } 
         else {
             $type = 'img';
         }
     echo $type;
 ?>

不太好。这相当于将if/elseif/else作为一行:

$tmp = 'this.ppt';
$tail = array_pop(explode('.',$tmp)); //'{file}'
$allow = array('ppt','pdf','docx');
$type = (in_array($tail, $allow) ? $tail : ($tail == 'doc' ? 'docx' : 'img'));

然而,我质疑你使用三元运算符的想法。正如@zerkms所指出的,您的原始代码更加清晰,而且工作正常。

您的原始代码:1。是可读的2。工作3。易于维护。你的新尝试:三个都不是。好吧,这是我从这里得到的最好答案。它清楚地说明了如何制作三元运算符(是的,因为有一段时间团队要求我使用它),谢谢。
$tmp = 'this.ppt';
$tail = array_pop(explode('.',$tmp)); //'{file}'
$allow = array('ppt','pdf','docx');
$type = (in_array($tail, $allow) ? $tail : ($tail == 'doc' ? 'docx' : 'img'));