我发现很难理解我在Foreach循环中面临的问题



我要做的是检查文件的文件扩展名,如果文件的扩展名与扩展名数组的任何元素匹配,那么我正在调用函数get_size()否则我显示的错误文件不匹配...问题是扩展名是否匹配我的代码的 else 语句被执行,但是如果扩展不匹配,我只想执行 else 语句 下面是我的代码

// getting the extension of the file 
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
// allowed extension array
$extensions= array('txt','xls','xlsm','xlsx','xlsm','csv' );
// foreach loop for checking if extensions matches or not
foreach ($extensions as $extres) 
{
    # code...
    if($extres===$ext)
    {
        get_size();
    }
    else 
    {
        # code...
        $once=1;
    }
}
if($once==1)
{
    exit("Sorry file not matched");
}

使用以下代码:

// getting the extension of the file 
$ext = pathinfo($file_name, PATHINFO_EXTENSIO-N);
// allowed extension array
$extensions= array('txt','xls','xlsm','xlsx','xlsm','csv' );
// foreach loop for checking if extensions matches or not
$once = 1;
foreach ($extensions as $extres) 
{
    # code...
    if($extres===$ext)
    {
        get_size();
        $once = 0;
    }
    else 
    {
        # code...
        //$once=1; //Remove the else part.
    }
}
if($once==1)
{
    exit("Sorry file not matched");
}

最新更新