如何在PHP中访问循环范围外的变量值?

时间:2021-08-29 20:26:49

I have run into a situation:

我遇到过这种情况:

I have a Multidimensional array that prints out the path levels. I wanna print the path before

我有一个打印出路径级别的多维数组。我想打印之前的路径

$maxlength = 4; // four levels

for($i = 0; $i<count($maxlength); $i++)
{
    $currentpath = $_GET['currentpath'];----->        /abc/def/g
    $path_level = explode('/',$currentpath);

    for($j = 0; $j<count($arr[$i]); $j++)
    {
         $temp = getcontentpath($arr[$i][$j]);
    }

    echo"<a href = '?path=$temp&action=abcd'>". $path_level[$i] ."</a>";
}

how can I access the value of temp outside the for loop scope?

如何在for循环范围外访问temp的值?

Thanks in advance..

提前致谢..

1 个解决方案

#1


-1  

As I messed up this answer at first, let's try to clear this up. As mentioned in the comments below, and as mentioned in the PHP documentation, PHP variables mostly only have a single scope, thus the variable $temp in this question should be accessible also outside the for loop, even though it was declared inside the loop. Therefore the problem isn't the variable scope.

当我最初弄乱这个答案时,让我们试着清除它。正如下面的评论中所提到的,并且如PHP文档中所提到的,PHP变量通常只有一个范围,因此在for循环之外,也应该可以访问此问题中的变量$ temp,即使它是在循环内声明的。因此问题不在于变量范围。

As Prashant found out him self, the problem was that the function was returning an empty value, thus the empty $temp

当Prashant发现他自己时,问题是该函数返回一个空值,因此是空的$ temp

#1


-1  

As I messed up this answer at first, let's try to clear this up. As mentioned in the comments below, and as mentioned in the PHP documentation, PHP variables mostly only have a single scope, thus the variable $temp in this question should be accessible also outside the for loop, even though it was declared inside the loop. Therefore the problem isn't the variable scope.

当我最初弄乱这个答案时,让我们试着清除它。正如下面的评论中所提到的,并且如PHP文档中所提到的,PHP变量通常只有一个范围,因此在for循环之外,也应该可以访问此问题中的变量$ temp,即使它是在循环内声明的。因此问题不在于变量范围。

As Prashant found out him self, the problem was that the function was returning an empty value, thus the empty $temp

当Prashant发现他自己时,问题是该函数返回一个空值,因此是空的$ temp