3

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

user765368
  • 19,590
  • 27
  • 96
  • 167

2 Answers2

4

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

See https://3v4l.org/amCJu


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

iainn
  • 16,826
  • 9
  • 33
  • 40
  • Isn't this only available starting php 5.6? – user765368 Aug 30 '18 at 20:55
  • 1
    @user765368 Yes, but seeing as you tagged your question with that version I assumed that wouldn't be an issue. – iainn Aug 30 '18 at 20:55
  • @user765368 Is there a reason that you have not yet accepted iainn's answer? Are you requiring a different technique? Do you have a bias against the splat operator? Are you _actually_ running an earlier version of php? – mickmackusa Aug 30 '18 at 22:03
  • Sorry guys, unfortunately I'm under php 5.5. I thought I was under 5.6 but that's not the case. So I'm gonna need a different answer. But thanks for that answer though, it's very cool. – user765368 Aug 30 '18 at 22:38
  • @user765368 I've added an option for earlier PHP versions – iainn Aug 31 '18 at 09:53
0

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

Rafael
  • 1,495
  • 1
  • 14
  • 25