精簡一個if語句

來源:互聯網
上載者:User
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 裡的字串插入麼……

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.