简体   繁体   中英

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. of times the loop is going to execute is decided by the user at run time. Any suggestion.?

Use array_fill maybe?

<?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

<?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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM