Mike
Mike

Reputation: 2900

In PHP how would I push the values of an array on to the end of itself

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

Answers (3)

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

James Sumners
James Sumners

Reputation: 14783

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

Upvotes: 2

Lizard
Lizard

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

Related Questions