Home > Backend Development > PHP Tutorial > 精简一个if语句

精简一个if语句

WBOY
Release: 2016-06-06 20:48:31
Original
1203 people have browsed it

<code>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;
</code>
Copy after login
Copy after login

大家看看上面的代码如何精简一下。

回复内容:

<code>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;
</code>
Copy after login
Copy after login

大家看看上面的代码如何精简一下。

$ext_arr 给取缔了,改成

<code class="lang-php">$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;
</code>
Copy after login

<code>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";
</code>
Copy after login

只是讨论精简的话,这个成功精简三行的样子而且字数上也少很多,两行的样子比较难看我就不缩了~

精简减不了 流程上可优化

<code>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;
</code>
Copy after login

<code class="lang-php">foreach (array('image', 'media', 'file') as $type) {
  if(in_array($file_ext, $ext_arr[$type])){
    $file_path="uploads/$type/$new_file_name";
    break;
  }
}
</code>
Copy after login

这代码高亮不支持高亮 PHP 里的字符串内插么……

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template