tags:

views:

64

answers:

3

Say I have an array:

$myArray = array("foo", "bar");

What is a good way to repeat the values in the array onto the end of the array so that:

$myArray = array("foo", "bar", "foo", "bar");

I thought maybe array_push would work like this:

array_push($myArray, $myArray);

but that actually pushes the array object and not the values of the array.

+4  A: 

you can do this with array_merge

$tmp = $myArray;

$myArray = array_merge($myArray, $tmp);

This will rely on you not worry about the array keys..

Another solution would be:

$tmp = $myArray;
foreach($tmp as $val) {
    $myArray[] = $val;
}
Lizard
+2  A: 

How about $myArray = array_merge($myArray, $myArray);?

jsumners
+1  A: 

If you explicitly want to duplicate the values of an array even if it is associative:

$myArray = array("foo" => "apple", "bar" => "orange");

$myArray = array_merge($tmp = array_values($myArray), $tmp);

The new array will contain ("apple", "orange", "apple", "orange") - note: it is now indexed.

Denis 'Alpheus' Čahuk