0

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.

2
  • Start with an empty array $db_columns = [] and add items with $db_columns[] = $value. It will expand by itself. Commented May 27, 2020 at 5:47
  • Does this answer your question? PHP - populate an array with variables by loop Commented May 27, 2020 at 5:59

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.