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