0

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
  • close vote .. array basic usage: php.net/manual/en/language.types.array.php Commented Jun 22, 2015 at 20:49
  • you are using $i and i. I think they all should be $i Commented Jun 22, 2015 at 21:17

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

6 Comments

thank you. That was so easy :D There my ignorance gets out. But thank you anyway
@Dagon Seems like New Zealand's internet takes a while :)
@Rizier123 its powered by sheep
9am winter, they are cold, let them have their morning coffee and bacon and eggs and they will perk up
i have to wait 2 minutes. Then i will accept your help :)
|
3

an alternative approach is to just use range():

$a=range(0,10);

2 Comments

Another funny method would be: $i = 1; while(($b[] = $i++) < 10); or just for($i = 1; ($b[] = $i++) < 10;); :)
@Rizier123 its php i can think of 32.5 ways to do it :-)

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.