![](/img/trans.png)
[英]How to get names of all the elements that appear through the for loop and put them into the associative array in PHP
[英]How to put all the numbers that come through "For loop" in one array in PHP
問題是我希望所有通過循環的數字都存儲在循環外的數組中,HTML 代碼是這樣的:
<div class="col-md-2 px-1 mb-1">
<input type="text" class="form-control" placeholder="Nr" name="var1">
</div>
<div class="col-md-2 px-1 mb-1">
<input type="text" class="form-control" placeholder="Nr" name="var2">
</div> ...
而 PHP 代碼是這樣的:
for($i=0; $i<=36; $i++){
if(isset($_GET["var$i"])){
$varCheck = $_GET["var$i"];
echo $varCheck;
$count++;
}
else{
"";
}
}
echo "<h1>".$count."</h1>";
$result = [];
for ($i = 0; $i < 36; $i++) {
$var = 'var' . $i;
if (!isset($_GET[$var]) || strlen(trim($_GET[$var])) === 0)
continue;
$result[] = $_GET[$var];
}
// array $result ready to use
print_r($result);
你可以在for循環的頂部聲明一個數組變量,
$num_arr = []; //empty array
在if
語句中,你可以做
`array_push($num_arr, $varCheck);` // this will add elements to the array every iteration
在循環之外,您可以打印數組內容:
`print_r($num_arr);`
在這種情況下, $count++
是不必要的,除非您真的想計算迭代次數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.