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,
];
CodePudding user response:
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;
}
CodePudding user response:
You are almost there. You can generate the array via range
and then prepend file
via array_map
like below:
<?php
$arr = array_map(fn($e) => 'file'. $e,range(1,5));
print_r($arr);
CodePudding user response:
If you want to keep your beginner-friendly and readable syntax, you can simply modify your code like such:
$arr = [];
for( $i = $start; $i < $start ($elements * $step); $i = $step ){
$arr[] = $text . $i;
}
Edit: be careful if your variables come from user input: a negative $step
could result in an infinite loop.
CodePudding user response:
If you want to give those parameters, then I believe you are looking at writing a function. In the function a for loop should achieve what you want.
function heaven_knows_why($text, $start, $elements, $step = 1)
{
$arr = [];
for( $i = $start, $j=1, $s=$start; $j <= $elements; $j , $i , $s = $step ){
$arr[] = $text . $s;
}
return $arr;
}
print_r(heaven_knows_why('duh', 1, 5));
print_r(heaven_knows_why('duh', 1, 5, 2));
RESULTS
Array
(
[0] => duh1
[1] => duh2
[2] => duh3
[3] => duh4
[4] => duh5
)
Array
(
[0] => duh1
[1] => duh3
[2] => duh5
[3] => duh7
[4] => duh9
)