首页 > 解决方案 > 如何在数组中搜索?

问题描述

我有代码:

$acceptFormat = array(
  'jpg' => 'image/jpeg',
  'jpg' => 'image/jpg',
  'png' => 'image/png'
);

if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
  throw new RuntimeException('Invalid file format.');
}

$mime = mime_content_type($_FILES['file']['tmp_name'][$i]);
if ($mime != "image/jpeg" && $mime != "image/jpg" && $mime != "image/png") {
   throw new RuntimeException('Invalid mime format.');
}

我有一个$acceptFormat允许文件格式的数组和两个 ify:

  1. if ($ mime! = "Image / jpeg" && $ mime! = "Image / jpg" && $ mime! = "Image / png")

  2. if ($ ext! = "Jpg" && $ ext! = "Jpeg" && $ ext! = "Png")

如果基于 acceptFormat 数组检查扩展名和 mime 类型,是否可以以某种方式修改它?

标签: phparrays

解决方案


尝试使用in_array(),array_keys()作为文件扩展名array_values()和mime。让我们来看看,

<?php

$acceptFormat = array(
  'jpg' => 'image/jpeg',
  'jpg' => 'image/jpg',
  'png' => 'image/png'
);

$ext ='jpg'; // demo value

if (!in_array($ext,array_keys($acceptFormat))) {
  throw new RuntimeException('Invalid file format.');
}

$mime = 'video/mkv'; // demo value

if (!in_array($mime,array_values($acceptFormat))) {
   throw new RuntimeException('Invalid mime format.');
}
?>

演示: https ://3v4l.org/aNdMM


推荐阅读