23

I have a number (e.g. 6) that is dynamically generated and I would like to fill an array with the numbers 1 through the dynamically generated number (in this example, 6):

array(1, 2, 3, 4, 5, 6);

The only way I know to do this at the moment is by using a for loop, but I'm wondering if there's a better way, something similar to array_fill. I looked at array_fill, but it doesn't look like it will take a number and increment it for a set number of times.

0

2 Answers 2

46

Use range:

$arr = range(1,6);
// Returns an array of elements from start to limit, inclusive.
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect, Thanks! (I'll accept the answer in 6 minutes - didn't realize they have a minimum amount of time I have to wait from asking the question to marking it as answered).
@Francis No problem! Just happy to help.
If you want the keys to be the same as the values, you should combine this with array_combine:
$num_range = range(1, 50); $resultNums = array_combine($num_range, $num_range);
5

This is what you are looking for:

range(1, 6)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.