将一些php语句转换为三元运算符

时间:2014-12-15 11:23:22

标签: php ternary-operator

这是我第一次学习三元运算符。我在这里尝试做的是将一些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;
 ?>

TP

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

1 个答案:

答案 0 :(得分:3)

不完全在那里。这相当于你的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所指出的那样,你的原始代码更清晰,并且工作正常。