Php 为什么我';m即使在不满足条件的情况下,循环仍会中断并出现错误?
我有以下代码片段:Php 为什么我';m即使在不满足条件的情况下,循环仍会中断并出现错误?,php,arrays,foreach,associative-array,break,Php,Arrays,Foreach,Associative Array,Break,我有以下代码片段: $aSupportedImages = array('jpg', 'gif', 'png'); foreach($vshare as $file) { if(!in_array(pathinfo($file, PATHINFO_EXTENSION), $aSupportedImages)) $errArr = 'File extension of image is wrong';
$aSupportedImages = array('jpg', 'gif', 'png');
foreach($vshare as $file) {
if(!in_array(pathinfo($file, PATHINFO_EXTENSION), $aSupportedImages))
$errArr = 'File extension of image is wrong';
echo $errArr;
break;
}
数组$vshare如下所示(print\r($vshare);
)的输出:
我不明白为什么循环总是被破坏,并出现错误“图像的文件扩展名是错误的”,即使文件扩展名存在于数组$aSupportedImages
中
请帮帮我
谢谢 您应该使用下面的代码,
因为图像名称是数组的
键
,并且您在扩展名检查中使用了值
编辑:正如其他用户所说,您的if
条件中缺少{}
括号
注意:如果只想执行一条语句,则不需要使用大括号。如果要执行多条语句,则必须将语句用大括号括起来
$aSupportedImages = array('jpg', 'gif', 'png');
foreach($vshare as $key=> $value) {
if(!in_array(pathinfo($key, PATHINFO_EXTENSION), $aSupportedImages))
{
$errArr = 'File extension of image is wrong';
echo $errArr;
break;
}
}
使用括号{}表示if块并检查print\r语句。使用括号表示
if
语句:
foreach($vshare as $file) {
if(!in_array(pathinfo($file, PATHINFO_EXTENSION), $aSupportedImages)) {
$errArr = 'File extension of image is wrong';
echo $errArr;
break;
}
}
另外,最好使用continue
而不是break
。中断析构函数循环,其他文件未被选中,但继续让我们检查其他文件,并仅在中断条件下显示错误。您可以尝试foreach($vshare as$name=>$value){
和pathinfo($name,pathinfo_扩展名)
foreach($vshare as $file) {
if(!in_array(pathinfo($file, PATHINFO_EXTENSION), $aSupportedImages)) {
$errArr = 'File extension of image is wrong';
echo $errArr;
break;
}
}