如何在for循环外获取for循环数据

How to get for loop data outside for loop

我想要 forloop 外的循环数据,但我只得到一个值

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">

               <select name="test[]"  multiple="multiple">
                    <option value="test">test</option>
                    <option value="mytesting">mytesting</option>
                    <option value="testingvalue">testingvalue</option>
                    </select>
                <input type="submit" value="Send" />
                   </form>


<?php
    $test=$_POST['test'];
    for($i=0;$i<count($test);$i++)
    {
    $tyy = $test[$i];
    }


?>

我想从循环中取出 $tyy

我希望循环数据在 forloop 之外,因为我只得到一个值

这是因为您在每次迭代时都重新分配它。所以将行更改为:

$tyy[] = $test[$i];
  //^^ See here, Now you are assign the value to a new array element every iteration

这样你就有了一个以后可以使用的数组

旁注:

1。您知道 $test 中已经有一个包含此数据的数组吗?但是如果你想要所有数据作为一个字符串,你可以使用这个(没有 for 循环):

$tyy = implode(", ", $test);

2。 $_SERVER["PHP_SELF"] 只是反映了你的 URL,所以这对 XSS 是开放的。您可以使用它来节省:

<?= htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8"); ?>

使用这个

$tyy[] = $test[$i];

或者您可以使用这个

连接值
$tyy = "";
for($i=0;$i<count($test);$i++)
    {
    $tyy .= $test[$i];
    }

print_r($tyy)

试试这个..

    $groupStr = "";
    for($i=0; $i< count($test); $i++)
        {
        $groupStr .= $test[$i];
        }

echo $groupStr;

使用 $tyy 作为数组并使用 array_push 方法将该数组填充到 for 循环中。

 $tyy = array();

 $test=$_POST['test'];
for($i=0;$i<count($test);$i++)
{
   array_push($tyy, $test[$i]);
}

您创建了一个变量,每次循环都会覆盖该变量,因此只能获取一个值。

如果要访问所有值,需要保存到一个数组而不是单个变量中,或者将所有值附加到一个值中

任一

//create an array of values in $tyy
$tyy = $_POST['test'];
//you can now access $tyy by looping through it.

$test = $_POST['test'];
$for($i = 0; $i<count($test); $i++)
{
  //list all the values with commas separating them.
  $tyy .= $test[$i].", ";
}

//view the contents by echoing it.
echo $tyy;

但是为什么要对 post 数据使用循环。 您的 $_POST['test'] 是自数组,因此您可以在没有 for 循环的情况下使用它。 $array = $_POST['test']; 试试这个。