php - 如何在数组中搜索?
问题描述
我有代码:
$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:
if ($ mime! = "Image / jpeg" && $ mime! = "Image / jpg" && $ mime! = "Image / png")
if ($ ext! = "Jpg" && $ ext! = "Jpeg" && $ ext! = "Png")
如果基于 acceptFormat 数组检查扩展名和 mime 类型,是否可以以某种方式修改它?
解决方案
尝试使用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.');
}
?>
推荐阅读
- python - 在 python 脚本的 SQL 命令中使用 sys.argv[1]
- javascript - 为什么我会收到 this.state 的错误“Unexpected token”?
- c# - 使用 SpaPrerenderingExtensions 时如何设置自定义标头并启用压缩?
- python - 打印变量名称的函数
- elasticsearch - 如何实现对共享文档的搜索
- spring-boot - 使用 docker-compose 时获取连接拒绝
- python - 你能告诉我 Python 中的 rep() 函数吗?
- r - 2组异质性指数
- javascript - 如何从 app.post 中的按钮检索值?
- blender - 使用python将mp4文件加载到ImageSequence剪辑中