将php语句的某些行转换为三元运算符
这是我第一次学习三元运算符。我在这里要做的是将php语句的一些行转换成三元运算符。有人能帮我检查一下我在这里做的事情是否正确吗。以及如何回应它。谢谢将php语句的某些行转换为三元运算符,php,ternary-operator,Php,Ternary Operator,这是我第一次学习三元运算符。我在这里要做的是将php语句的一些行转换成三元运算符。有人能帮我检查一下我在这里做的事情是否正确吗。以及如何回应它。谢谢 <?php $tmp = 'this.ppt'; $tail = array_pop(explode('.',$tmp)); //'{file}' $allow = array('ppt','pdf','docx'); if (in_array($tail, $allow) {
<?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;
?>
不太好。这相当于将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所指出的,您的原始代码更加清晰,而且工作正常。您的原始代码:1。是可读的2。工作3。易于维护。你的新尝试:三个都不是。好吧,这是我从这里得到的最好答案。它清楚地说明了如何制作三元运算符(是的,因为有一段时间团队要求我使用它),谢谢。
$tmp = 'this.ppt';
$tail = array_pop(explode('.',$tmp)); //'{file}'
$allow = array('ppt','pdf','docx');
$type = (in_array($tail, $allow) ? $tail : ($tail == 'doc' ? 'docx' : 'img'));