Is there a function like array_fill
, that lets me fill an array with the same string ("field_"), combined with an increasing $i variable like this:
private function fields() {
$result = [];
foreach(range(1,44) as $i) {
$result[] = "field_$i";
}
return $result;
}
I know there is a bunch of functions in php and I would love to have this in one line (if possible).
I found this, seems to be 3 times faster than foreach and it's the shortest solution I could find so far.
$prefixed_array = preg_filter('/^/', 'prefix_', $array);
You could use array_map
to remove the need for an explicit loop, but I don't think putting it on one line gains you much in terms of readability:
$results = array_map(function ($i) { return "field_{$i}"; }, range(1, 44));
=
Array
(
[0] => field_1
[1] => field_2
...
Php's foreach
loops actually allow you to access the current index
private function fields() {
$result = [];
foreach(range(1,44) as $k => $i) {
$result[] = "field_$k";
}
return $result;
}