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

convert some lines of php statement into ternary operator

这是我第一次学习三元运算符。我在这里尝试做的是将php语句的某些行转换为三元运算符。谁能帮我检查一下我在这里做的是否正确。以及如何回声。谢谢。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 <?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;
 ?>

TP

1
  $tail = ($type == $tail ? 'ppt','pdf','docx' : ($type == 'doc') ? 'docx' : 'img()'))


不完全在那里。这等效于您的if / elseif / else作为单行:

1
2
3
4
$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指出的那样,您的原始代码更清晰易读,并且可以正常工作。