Joran Den Houting
Joran Den Houting

Reputation: 3163

Number to counter

I have a number, let's say it's 5 for now. The thing I want is to get an array from 0 to 5.

So as an example:

$input = 5;
// Do something
$output = array(0,1,2,3,4,5);

I did something like this:

$i = 0;
$input = 5;
$output = array();
while($i <= $input) {
    $output[] = $i;
    $i++;
}

A quick print_r($output); will result in:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

Looks good, but I was hoping for a smaller and quicker solution. Any suggestions? Is their a PHP function I'm missing/don't know of?

Upvotes: 1

Views: 45

Answers (3)

Ana Claudia
Ana Claudia

Reputation: 507

$input = 5;
$output = array();
for($i=0; $i<=$input; $i++) {
  $output[] = $i;
}

Upvotes: 0

Paul Facklam
Paul Facklam

Reputation: 1633

$input = 5;
$output = array();
for($i = 0; $i <= $input; $i++) {
    $output[] = $i;
}

Upvotes: 1

Florent
Florent

Reputation: 12420

Maybe range()?

$output = range(0, $input);
print_r($output);

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

Upvotes: 5

Related Questions