douzhao1912 2013-03-21 14:49
浏览 37
已采纳

PHP foreach给出了错误的结果

I've searched for this for quite a while now and I cannot figure out why my code isn't working how it appears. I'm not sure if I'm having a block or anything but here goes:

$start = 1;
$sstart = strval($start);
$scan = scandir('upload');
$result = null;
while($result==null)
    {
        foreach($scan as $value)
        {
            if(strpos($value,$start) == false)
                {
                    $result = $start;
                    break 2;
                }
            else
                {
                    $start = $start + 1;
                    break;
                }
        }
    }

Essentially, I want to scan my directory 'upload' for any files with the number held in $start. If this value ISN'T found, then $result takes the value of $start and the while() loop ends. Otherwise I increment $start and proceed to check every file in the directory again.

Now I have a very similar function like this running on another page that works flawlessly. However this always seems to stop at 1.

There is DEFINITELY a file in my upload folder called showreel1.wmv and it definitely scans this. (Have echo'd the scandir array) However, it never seems to switch to the else block but carries on setting $result as if it never found the value '1'.

I have also tried using $sstart in the strpos() function and it has no effect, this of course changes the value of $start into a string.

Can you guys shed any light on this for me please?

  • 写回答

4条回答 默认 最新

  • doushi1957 2013-03-21 14:58
    关注

    I hope I understood what you're trying to do, try with this:

    while($result === null)
    {
        $found = false;
        foreach($scan as $value)
        {
            if(strpos($value,$start) !== false)
            {
                $found = true;
                $start = $start + 1;
                break;
            }
        }
    
        if(!$found)
        {
            $result = $start;
            break;
        }
    }
    

    By the way, you should learn how to use === operator, it's essential to correctly use strpos()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?