循环外的变量

时间:2011-06-14 13:49:29

标签: php variables loops foreach

我想再次使用所有$gamename个变量:

foreach($gamelist as $e){
            $chunks = explode('/',$e->nodeValue);
            $gamename = substr($chunks[2],0,-5);
            echo $gamename;
            echo "<br/>";
        }
 getObjects($fullPath,$folder,$gamename)

正如我所看到的,$gamename在foreach循环之外是未定义的。

3 个答案:

答案 0 :(得分:3)

out循环$gamename具有最后一次迭代的值,

undefined如果循环永不运行($gamelist为空)

答案 1 :(得分:3)

根据您的编辑,您需要以下内容:

$gamenames = array();

foreach($gamelist as $e){
            $chunks = explode('/',$e->nodeValue);
            $gamename = substr($chunks[2],0,-5);
            echo $gamename;
            $gamenames[] = $gamename;
            echo "<br/>";
        }

// $gamenames is an array containing all game names
getObjects($fullPath,$folder,$gamenames[0])    // for the first game name

答案 2 :(得分:2)

for循环具有局部作用域,这意味着在循环执行之外声明它们内部的变量不存在,如果你想重用你应该在循环之外创建它们的$ gamename变量,请参考@jeroen的帖子示例