Ash Burlaczenko
Ash Burlaczenko

Reputation: 25465

How to duplicate values in a flat, indexed array? (Append all elements to end of array in order)

Say I had this code

$x = array("a", "b", "c", "d", "e");

Is there any function that I could call after creation to duplicate the values, so in the above example $x would become

array("a", "b", "c", "d", "e", "a", "b", "c", "d", "e");

I thought something like the following but it doesn't work.

$x = $x + $x;

Upvotes: 13

Views: 14436

Answers (7)

hejdav
hejdav

Reputation: 1367

If N duplicates of the elements is needed, array_fill helps:

https://3v4l.org/3G8c5#v8.2.7

$data = ['a', 'b', 'c'];
$multiplicator = 3;
$multipliedData = array_merge(...array_fill(0, $multiplicator, $data));

var_export($multipliedData);
// array (0 => 'a', 1 => 'b', 2 => 'c', 3 => 'a', 4 => 'b', 5 => 'c', 6 => 'a', 7 => 'b', 8 => 'c',)

Upvotes: 1

mickmackusa
mickmackusa

Reputation: 47904

First and foremost, it should be asked: Why is it beneficial to push redundant data into your input array?

If you need to access the data in a loop for presentation purposes, you can spare the array bloat and merely change how the elements are iterated.

For instance, you could just call two separate foreach() loops on the original array.

foreach ($x as $v) {
    echo "$v\n";
}
foreach ($x as $v) {
    echo "$v\n";
}

Or with a single for() loop, you could use a modulus calculation to access the appropriate element. Demo

$count = count($x);
for ($i = 0, $limit = $count * 2; $i < $limit; ++$i) {
    echo $x[$i % $count] . "\n";
}

Now, if you do, indeed, need to append the array's values after the original indexed array and maintain the flat, indexed structure, then array_merge() is sensible and intuitive, but not the only way.

With the spread/splat operator (...), you can unpack the input elements twice inside of a new array. While this is a functionless approach and uses less characters, it has a habit of not being terribly efficient. Demo

$result = [...$x, ...$x];

Perhaps my most-preferred approach would be to call array_push() and unpack the elements of the array when pushing data into the original array. I don't know how it performs versus array_merge(), but I find it intuitive/literal about the operation of appending data to the original array. Demo

array_push($x, ...$x);

For a functional-style approach, array_reduce() can have its initial data payload set via its third parameter (in this case the whole input array), then merely push each element one-at-a-time into the result array. Demo

var_export(
    array_reduce(
        $x,
        function($result, $v) {
            $result[] = $v;
            return $result;
        },
        $x
    )
);

Although it is unintuitive to use for this task, array_merge_recursive() works just like array_merge() when fed the indexed array twice. Demo

$result = array_merge_recursive($x, $x)

After all that, I should warn that there are some techniques to avoid.

  1. $result = array_replace($x, $x); is pointless.
  2. The array union operator is useless.
  3. array_pad() is unsuitable because its third parameter can only receive one value.
  4. array_map() returns the same number of elements in its result as its input array.
  5. array_merge(...array_fill(0, 2, $x)) works, but why call 2 functions when there 0 and 1-function techniques to enjoy.

Upvotes: 0

marramgrass
marramgrass

Reputation: 1411

$x = array_merge($x, $x);

Or you could go looping and duplicating, if you preferred.

Upvotes: 0

Nasreddine
Nasreddine

Reputation: 37838

This should do the trick:

$x = array("a", "b", "c", "d", "e");
$x = array_merge($x,$x);

Upvotes: 2

Mark Grey
Mark Grey

Reputation: 10257

$x = array("a", "b", "c", "d", "e");

$x = array_merge($x,$x);

Merging an array onto itself will repeat the values as duplicates in sequence.

Upvotes: 22

thetaiko
thetaiko

Reputation: 7834

php > $x = array("a", "b", "c", "d", "e");
php > print_r(array_merge($x, $x));

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => a
    [6] => b
    [7] => c
    [8] => d
    [9] => e
)

Upvotes: 6

max_
max_

Reputation: 24481

You could loop through the array and that each variable to a separate duplicate array. Here is some code off the top of my head:

$x = array("a", "b", "c", "d", "e");
$duplicateArray = $array;

foreach ($x as $key) {
    $duplicateArray[] = $key;
}

foreach ($x as $key) {
    $duplicateArray[] = $key;
}

Upvotes: 0

Related Questions