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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With