[英]Dynamically populate php array using foreach loop
How can I implement the code: 我如何实现代码:
$numberList3 = array();
for($i = 0; $i < 10; $i++)
{
$numberList3[$i] = $i;
}
print_r($numberList3);
Using a foreach loop as the no. 使用foreach循环作为否。 of times the loop is going to execute is decided by the user at run time.
循环执行的时间由用户在运行时决定。 Any suggestion.?
有什么建议吗?
Use array_fill maybe? 也许使用array_fill ?
<?php
$n = 10;
$arr = array_fill(0,$n,0);
foreach($arr as $k => $v) {
$arr[$k] = $k;
}
print_r($arr);
Or, as suggested by @ deceze , use range 或者,如@ deceze所示 ,使用范围
<?php
$n = 10;
$arr = array();
foreach(range(0,$n-1) as $v) {
$arr[$v] = $v;
}
print_r($arr);
Or when the value is the same as the key, you can use just this: 或者,当值与键相同时,可以使用以下命令:
<?php
$n = 10;
$arr = range(0,$n-1);
// no foreach needed
print_r($arr);
foreach() works for object and array not for a single value. foreach()适用于对象和数组,不适用于单个值。
What you can do create an array or object from users input. 您可以根据用户输入创建数组或对象。
like: 喜欢:
$userInput = 10;
$forEachArray = array_fill(0, $userInput, 0);
$arrayToDisplay = array();
foreach($forEachArray as $key){
$arrayToDisplay[$key] = $key;
}
print_r($arrayToDisplay);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.