【问题标题】:convert some lines of php statement into ternary operator将几行php语句转换为三元运算符
【发布时间】:2014-12-15 11:23:21
【问题描述】:

这是我第一次学习三元运算符。我在这里要做的是将一些 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. 可读 2. 有效 3. 易于维护。你的新尝试:3个都不是。

标签: php ternary-operator


【解决方案1】:

不完全在那里。这相当于你的 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 指出的那样,您的原始代码更清晰易读。

【讨论】:

  • 好的,这是我从这里得到的最佳答案。说清楚了怎么做三元算子(是的,因为有一段时间团队让我用这个)谢谢。
猜你喜欢
  • 2021-07-09
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 2017-05-30
  • 2016-05-22
  • 2019-10-13
相关资源
最近更新 更多