12

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 this but it doesn't work

$x = $x + $x;

Ash Burlaczenko
  • 23,106
  • 15
  • 65
  • 96

5 Answers5

20
$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.

DeaconDesperado
  • 9,429
  • 8
  • 44
  • 76
6
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
)
thetaiko
  • 7,748
  • 2
  • 32
  • 49
  • @Ash - there is also a good summary page that describes all the array functions in PHP quite well: http://php.net/manual/en/ref.array.php – thetaiko Nov 22 '11 at 22:51
2

This should do the trick:

$x = array("a", "b", "c", "d", "e");
$x = array_merge($x,$x);
Nasreddine
  • 35,089
  • 17
  • 75
  • 92
0

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;
}
max_
  • 23,337
  • 38
  • 120
  • 209
0
$x = array_merge($x, $x);

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

marramgrass
  • 1,411
  • 14
  • 17