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;
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
Using the has() method In the above implementation, the output array can have duplicate elements if the elements have occurred more than twice in an array. To avoid this and for us to count the number of elements duplicated, we can make use of the use() method.
To merge the duplicate value in a multidimensional array in PHP, first, create an empty array that will contain the final result. Then we iterate through each element in the array and check for its duplicity by comparing it with other elements.
$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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With