Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to create an incremental array with PHP?

Tags:

arrays

php

I just would like to know what is the easiest way to create an incremental array?

$myarray = array('test1', 'test2', 'test3', 'test4, 'test5', 'test6', 'test7', 'test8');

Of course I can use a "for" loop...

for ($i=1;$i<=8;$i++){
    $myarray[] = 'test'.$i;
}

...but do you know if I can do better with a native php function (or something like that)?

like image 963
Dacobah Avatar asked Nov 04 '22 11:11

Dacobah


1 Answers

Here's a method using array_map() along with range():

$array = array_map(function($n){ return "test" . $n;}, range(1, 8));

print_r($array);
Array
(
    [0] => test1
    [1] => test2
    [2] => test3
    [3] => test4
    [4] => test5
    [5] => test6
    [6] => test7
    [7] => test8
)

I'm not sure I would choose to use this over a plain old loop like your example though. The only real benefit is the ease of use range() adds over an incremental for loop. The added complexity of array_map()'s anonymous function probably isn't worth it for a case this simple.

like image 124
Michael Berkowski Avatar answered Nov 10 '22 18:11

Michael Berkowski