为什么即使不满足条件,循环也会中断并出现错误?
Why I'm the loop is breaking and getting error even after not satisfying the condition?
我有以下代码片段:
$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);
的输出):
Array
(
[IMG_0004.jpg] => Array
(
[0] => https://www.filepicker.io/api/file/UYUkZVHERGufB0enRbJo
)
)
我不明白为什么即使在数组 $aSupportedImages
?
中存在具有扩展名的文件之后,循环总是被破坏并出现错误 "File extension of image is wrong"
请帮助我。
谢谢。
你应该使用下面的代码,
因为图像名称是数组的 key
,而您在扩展检查中使用了 value
编辑 :正如其他用户所说,您的 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
。 Break destruct loop 和其他文件不检查,但继续让检查其他文件并仅在破坏条件下显示错误。
我有以下代码片段:
$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);
的输出):
Array
(
[IMG_0004.jpg] => Array
(
[0] => https://www.filepicker.io/api/file/UYUkZVHERGufB0enRbJo
)
)
我不明白为什么即使在数组 $aSupportedImages
?
请帮助我。
谢谢。
你应该使用下面的代码,
因为图像名称是数组的 key
,而您在扩展检查中使用了 value
编辑 :正如其他用户所说,您的 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
。 Break destruct loop 和其他文件不检查,但继续让检查其他文件并仅在破坏条件下显示错误。