1

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).

Basti
  • 606
  • 1
  • 12
  • 22

3 Answers3

4

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
  ...
iainn
  • 16,826
  • 9
  • 33
  • 40
  • you are right, thanks for your response! I was hoping for something shorter.. like a single method call: array_fill($i = 1, 44, "field_$i"); or so :) – Basti Sep 26 '17 at 17:04
  • I mean, you've basically got the function you need in the question - just move the prefix and the range parameters into function arguments, and declare it as `array_prefix($from, $to, $prefix)` or something similar. Then you can use it wherever you like as `array_prefix(1, 44, 'field_');` – iainn Sep 26 '17 at 17:10
1

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);
Basti
  • 606
  • 1
  • 12
  • 22
0

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;
}
William Perron
  • 1,288
  • 13
  • 18