Reputation: 2900
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.
Upvotes: 1
Views: 766
Reputation: 4212
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.
Upvotes: 1
Reputation: 45062
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;
}
Upvotes: 4