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()')) |
- 您的原始代码:1.可读2.可以工作3.易于维护。您的新尝试:都不是3。
不完全在那里。这等效于您的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指出的那样,您的原始代码更清晰易读,并且可以正常工作。
- 好的,这是我从这里得到的最佳答案。这很清楚如何使三元运算符(是的,因为有一段时间团队要求我使用它)谢谢。