Home >Backend Development >PHP Tutorial >Invalid argument supplied for foreach()

Invalid argument supplied for foreach()

WBOY
WBOYOriginal
2016-06-06 20:47:302138browse

<code>$data[0] = array(
            "file"=>"jquery",
            "file"=>"bootstrap"
        );
    foreach($data as $val){
        $link = $val['file'].'.js';
    }
    foreach($link as $val){
        $links = "<script src="%5C'%22.%24val%5B'file'%5D.%22%5C'"></script>";
    }
    print_r($links);
</code>

输出:
Warning: Invalid argument supplied for foreach() in F:\xampp\htdocs\xampp\cms\Ajax\index3.php on line 10

Notice: Undefined variable: links in F:\xampp\htdocs\xampp\cms\Ajax\index3.php on line 13

回复内容:

<code>$data[0] = array(
            "file"=>"jquery",
            "file"=>"bootstrap"
        );
    foreach($data as $val){
        $link = $val['file'].'.js';
    }
    foreach($link as $val){
        $links = "<script src="%5C'%22.%24val%5B'file'%5D.%22%5C'"></script>";
    }
    print_r($links);
</code>

输出:
Warning: Invalid argument supplied for foreach() in F:\xampp\htdocs\xampp\cms\Ajax\index3.php on line 10

Notice: Undefined variable: links in F:\xampp\htdocs\xampp\cms\Ajax\index3.php on line 13

参考意见如下:

  1. 你的$link是一个string。你把string放到foreach里能不出错么……

  2. 在数组中加入元素的话建议你这么写$links[]=""

  3. 若你下次再碰到这类问题,就写var_dump($你的foreach里的第一个元素)这样会输出一个结构树来看下你这个变量的类型和包含的子元素及类型

  4. 可以用is_array来判断其是否为array

与此题无关的吐槽:
只有function才限制PHP的变量范围,即使是For和Foreach内部建立的变量也木有问题,因为有预编译到OPcode的阶段。
亲测如下:

<code class="lang-PHP">foreach(array(1,2,3) as $i){
    $var=$i;
}
var_dump($var);
</code>

可以直接输出int(3)的。
这个跟Java等严谨的语言差异很大啊,这方面资料很不好找。大家别以为是错的。但是这么写感觉好别扭,我果然还是不习惯于弱类型语言啊。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn