Let's say that I have a variable number variable $num which can contain any interger and I have array $my_array which contains some values like:
$my_array = ['a','b','c'];
I would like to merge another dynamic array $dyn_array with $my_array based on the value of $num for example.
Let's say $num = 2, I would like to have:
$merged_array = array_merge($my_array, $dyn_array, $dyn_array);
If $num = 3, I would like to have:
$merged_array = array_merge($my_array, $dyn_array, $dyn_array, $dyn_array);
So basically adding $dyn_array inside the array_merge depending on the value of $num.
How would I go about doing something like that?
Thanks for any help
You can use ...
(the "splat" operator) to expand the result of a call to array_fill
, which will merge as many copies of $dyn_array
as you need:
$num = 2;
$result = array_merge($my_array, ...array_fill(0, $num, $dyn_array));
For PHP versions earlier than 5.6, which don't support ...
, you can use the following line instead:
$result = array_reduce(
array_fill(0, $num, $dyn_array),
function($carry, $item) { return array_merge($carry, $item); },
$my_array
);
which iterates over the same copies from the array_fill
call, merging them into the result one at a time. See https://3v4l.org/s7dvd
I have a somehow longer workaround considering you are using PHP 5.5.
$my_array = ['a','b','c'];
$array_main[] = &$my_array;
$array_main[] = [1, 2];
$array_main[] = [4, 5];
$array_main[] = ['etc', 'bla'];
$iterations = count($array_main);
for ($i = 1; $i < $iterations; $i++) {
$array_main[0] = array_merge(
$array_main[0],
$array_main[$i]
);
}
echo '<pre>';
print_r($my_array);
I decided to add the array as the first key and by reference, so we will always have it updated.
Then I loop by the amount of items - 1, adding one by one inside the original array.
The code is tested here: https://3v4l.org/LF0CR