Katie Katie - 1 year ago 72
PHP Question

Replacing the beginning of an array with another

I need to replace the beginning of an array with a second array, with the second array replacing as many items as it has, but leaving the rest of the original array in tact.

So, for example:

$receiver = [1,2,3,4,5];
$setter = [10,11,12];

would result in [10,11,12,4,5]

Here is code that currently works:

// iterate through the values overwriting the receiver
for ($i=0; $i<count($setter); ++$i) {

// if the stored width is big enough to accept this value
if ($i < count($receiver)) {

// copy the value
$receiver[$i] = $setter[$i];


But is there a better way?

Answer Source

This will do it for indexed arrays

$receiver = array_slice($setter,0,count($receiver)) + $receiver;

Live demo

How it works: array_slice will cut off the end of $setter if necessary to ensure that it's not longer than $receiver. Then the + operator will keep the left handside as it is, but if $receiver is longer, it will append its extra elements to the end of the array on the left.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download