how to fill an array in a loop with variables which are created in this loop (in php)?

58 views Asked by At

I want to generate or fill an array in a loop with variables (in php). But these variables are written in this loop.

so an example:

$i = 1;
while(i<10){
    $a = array("$i","$i","$i");  
    i++;
}

the secound and the third i variables should be added in the next passage. So finaly the array will include the numbers from 0 to 10. I found something with $$variables but i don't thing there is a usefull usage.

What is a possible way for this? Thank you :)

2

There are 2 answers

6
Rizier123 On BEST ANSWER

I think you are stuck, that you don't know how to add an element to an array, which is something pretty basic.

Just add an element to your array every iteration like this:

$i = 0;
while($i < 10) { //If you want 0 - 10 including 10, just change '=' to '<='
    $a[] = $i;  
    $i++;  //Assuming, that the missing dollar signs are typos, since you already did it right once
}

Read up more about arrays here: http://php.net/manual/en/language.types.array.php

2
AudioBubble On

an alternative approach is to just use range():

$a=range(0,10);