如何在循环外获取 while 循环值

How to take while loop values outside of the loop

我正在尝试从 cookie 中获取值,然后使用 explode() 转义所有逗号,并使用 while 循环循环 cookie 中的所有值。

当我尝试使用下面的代码在 while 循环中显示值时,它起作用了:

echo $hey= '<span>'.$result[$counter].'</span>  ';

但我需要访问循环外的值,而这段代码没有给出任何输出。

$cookie_value=$_COOKIE["chords"];  
$counter = 0;
$result=explode(",", $cookie_value);

$array_el_lenght = count($result);

while ($counter<=$array_el_lenght) {
  $hey= '<span>'.$result[$counter].'</span>  ';
  $counter++;
}

echo $hey;

您的 while 循环循环次数过多,因为数组的最后一个元素位于索引 $array_el_lenght - 1 处。另外,不要忘记连接您的结果(编辑:我只是猜测这就是您想要做的),而不仅仅是重新分配 $hey! ;-)

试试这个:

$cookie_value=$_COOKIE["chords"];  
$counter = 0;
$result=explode(",", $cookie_value);

$array_el_lenght = count($result);

$hey = "";
while ($counter < $array_el_lenght) {
  $hey .= '<span>'.$result[$counter].'</span>  ';
  $counter++;
}
echo $hey;

$hey 是在循环内部定义的,所以它的作用域以循环结束。如果你想从循环外访问它,你也应该在循环外定义它:

$hey = NULL;
while ($counter<=$array_el_lenght) {
    $hey= '<span>'.$result[$counter].'</span>  ';
    $counter++;
}
if ($hey) {
    echo $hey;
}

您正在尝试访问 $result 的未定义偏移量,您的代码正在尝试访问不存在的 $result[count($result)],您需要替换 while 语句,因此在您的最后一个迭代索引位于 count($result)-1

while ($counter < $array_el_lenght) { //Replaced <= with <
   $hey= '<span>'.$result[$counter].'</span>';
   $counter++;
   echo $hey; // will output the current iteration
 }

// echo $hey; //Will output the content of  last while iteration