繁体   English   中英

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

[英]convert some lines of php statement into 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()'))

不太好。 这相当于你的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指出你的原始代码更清晰,它工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM