5

What's the fastest way to populate an array with the numbers 1-100 in PHP? I want to avoid doing something like this:

$numbers = '';

for($var i = 0; i <= 100; $i++) {
    $numbers = $i . ',';
}

$numberArray = $numbers.split(',');

It seems long and tedious, is there a faster way?

2
  • Do you want 1 - 100 as you ask in your question, or 0 - 100 as your code and the one by Jason246 suggests? Commented Sep 3, 2009 at 14:19
  • I got the general gist of his answer... He could've answered in response to my pseudo code which starts with 0 in the loop. Nice catch though. Commented Sep 3, 2009 at 14:22

2 Answers 2

25

The range function:

$var = range(0, 100);
Sign up to request clarification or add additional context in comments.

Comments

8

range() would work well, but even with the loop, I'm not sure why you need to compose a string and split it - what's wrong with simply:

$numberArray = array();
for ($i = 0; $i < 100; $i++)
  $numberArray[] = $i;

1 Comment

The code was just an example, nonetheless your way is of course much more efficient than mine :)

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.