PHP - duplicate values ​​in an array

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 will become

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

I thought something like this, but it does not work.

$ x = $ x + $ x;

+6
source share
5 answers
 $x = array("a", "b", "c", "d", "e"); $x = array_merge($x,$x); 

Merging the array onto itself will repeat the values ​​as repeating in the sequence.

+9
source
 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 ) 
+6
source

This should do the trick:

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

You can iterate over the array and each variable into a separate duplicate array. Here is the code on my head:

 $x = array("a", "b", "c", "d", "e"); $duplicateArray = $array; foreach ($x as $key) { $duplicateArray[] = $key; } foreach ($x as $key) { $duplicateArray[] = $key; } 
0
source
 $x = array_merge($x, $x); 

Or you can go in a loop and duplicate if you want.

0
source

Source: https://habr.com/ru/post/902161/


All Articles