Skip to content
Advertisement

How to populate an array dynamicaly using a loop in PHP?

How to populate an array dynamicaly using a for loop in PHP?

eg: Here is an array…

    static protected $db_columns = [' ',' '];

… and here is the for loop

    $qcount = 4;
    for($i=1; $i<=$qcount; $i++) {

The array should become

     static protected $db_columns = ['1','2',3','4'];

Depending on the $qcount the array should expand. Please help.

Advertisement

Answer

you can initialize array like this

$db_columns = array();

add value using a loop

$qcount = 4;
for($i=1; $i<=$qcount; $i++) {
 array_push($db_columns,$i);
}

and after loop, you can check with printing array

var_dump($db_columns);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement