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 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件