Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_merge based on integer value

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

like image 210
user765368 Avatar asked Feb 19 '26 15:02

user765368


1 Answers

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

like image 72
iainn Avatar answered Feb 21 '26 05:02

iainn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!