精简一个if语句
程序员文章站
2022-04-10 19:43:39
...
if(in_array($file_ext, $ext_arr['image']))
$file_path='uploads/image/'.$new_file_name;
if(in_array($file_ext, $ext_arr['media']))
$file_path='uploads/media/'.$new_file_name;
if(in_array($file_ext, $ext_arr['file']))
$file_path='uploads/file/'.$new_file_name;
大家看看上面的代码如何精简一下。
回复内容:
if(in_array($file_ext, $ext_arr['image']))
$file_path='uploads/image/'.$new_file_name;
if(in_array($file_ext, $ext_arr['media']))
$file_path='uploads/media/'.$new_file_name;
if(in_array($file_ext, $ext_arr['file']))
$file_path='uploads/file/'.$new_file_name;
大家看看上面的代码如何精简一下。
把 $ext_arr
给取缔了,改成
$types_of_extensions = array(
'jpg' => 'image',
'png' => 'image',
'gif' => 'image',
'rmvb' => 'media',
'mp3' => 'media',
'doc' => 'file',
'pptx' => 'file'
/* ... and many more, whatever u want */
);
$file_path = 'uploads/' . $types_of_extensions[$file_ext] . '/' . $new_file_name;
foreach(array('image', 'media', 'file') as $type)
foreach($ext_arr[$type] as $t) @$ext[$t] = $type;
$file_path = "uploads/{$ext[$file_ext]}/$new_file_name";
只是讨论精简的话,这个成功精简三行的样子而且字数上也少很多,两行的样子比较难看我就不缩了~
精简减不了 流程上可优化
if(in_array($file_ext, $ext_arr['image']))
$file_path='uploads/image/'.$new_file_name;
elseif(in_array($file_ext, $ext_arr['media']))
$file_path='uploads/media/'.$new_file_name;
elseif(in_array($file_ext, $ext_arr['file']))
$file_path='uploads/file/'.$new_file_name;
foreach (array('image', 'media', 'file') as $type) {
if(in_array($file_ext, $ext_arr[$type])){
$file_path="uploads/$type/$new_file_name";
break;
}
}
这代码高亮不支持高亮 PHP 里的字符串内插么……