This is my first time in learning ternary operator. What I am trying to do here is to convert some lines of php statement into ternary operator. Can anyone please help me to check if what I am doing here is correct. And how to echo it. Thanks.
<?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()'))
Not quite there. This is the equivalent of your if / elseif / else as a single line:
$tmp = 'this.ppt';
$tail = array_pop(explode('.',$tmp)); //'{file}'
$allow = array('ppt','pdf','docx');
$type = (in_array($tail, $allow) ? $tail : ($tail == 'doc' ? 'docx' : 'img'));
However I question your idea to use a ternary operator hear. As @zerkms pointed out your original code is more legible and it works fine.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments