I want to create a function that generates an array that 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 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 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 = [];
$s = $start;
for( $i = $start; $i <= $elements; $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
)
CodePudding user response:
You can choose a functional style or classic loop approach using your parameters. I am using the same equation to determine the end of the range -- so that the correct number of elements is generated. (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 loop(
$text = 'file',
$elements = 5,
$start = 1,
$step = 1
) {
$result = [];
$end = $start $elements * $step - 1;
while ($start <= $end) {
$result[] = $text . $start;
$start = $step;
}
return $result;
}
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.