Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Duplicate values in an array

Tags:

arrays

php

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;

like image 776
Ash Burlaczenko Avatar asked Nov 22 '11 22:11

Ash Burlaczenko


People also ask

How do you duplicate values in an array?

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.

Can array have duplicate values?

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.

How can we get duplicate values in multidimensional array in PHP?

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.


2 Answers

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

like image 107
DeaconDesperado Avatar answered Oct 09 '22 12:10

DeaconDesperado


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
)
like image 26
thetaiko Avatar answered Oct 09 '22 12:10

thetaiko