Populate array with values formed by concatenating a range of numbers to a static string

Issue

I want to create a function that generates an array of elements which consist of incremented numbers appended to a static string/prefix and looks like this:

$arr = [
    'file1',
    'file2',
    'file3',
    'file4',
    'file5',
];

I know I can create a simple loop like this one:

$arr = [];
for( $i = 1; $i <= 5; $i ++ ){
    $arr[] = 'file' . $i;
}

But the idea is to give the parameters $text = file, $start = 1, $elements = 5 and optional $step = 1 and use built-in php functions to achieve it.

I tried something like:

$arr = array_merge( array_fill( 0, 5, 'file' ), range( 1, 5, 1 ) );

But from that one I got

$arr = [
    "file",
    "file",
    "file",
    "file",
    "file",
    0,
    1,
    2,
    3,
    4,
    5,
];

Solution

You can choose a functional style or classic loop approach using your parameters. I am using the same equation in map() and whileloop() to determine the end of the range and avoid the use of an additional counter variable. The forloop() function is a little easier to understand, but has to maintain an extra variable which must be incremented to get the number of elements right. (Demo)

function map($text = 'file', $elements = 5, $start = 1, $step = 1) {
    $end = $start + $elements * $step - 1;
    return array_map(
        fn($i) => $text . $i,
        range($start, $end, $step)
    );
}

Or

function whileloop($text = 'file', $elements = 5, $start = 1, $step = 1) {
    $result = [];
    $end = $start + $elements * $step - 1;
    while ($start <= $end) {
        $result[] = $text . $start;
        $start += $step;
    }
    return $result;
}

Or

function forloop($text = 'file', $elements = 5, $start = 1, $step = 1) {
    $result = [];
    for ($i = 0; $i < $elements; ++$i, $start += $step) {
        $result[] = $text . $start;
    }
    return $result;
}

Answered By – mickmackusa

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.