Katie
Katie

Reputation: 2693

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?

Upvotes: 0

Views: 44

Answers (3)

user6604077
user6604077

Reputation: 11

Here is a simple code of your requirement.

// iterate through the values overwriting the receiver 
for ($i = 0; $i < count($receiver); ++$i) {
    if (isset($setter[$i])) {
        // copy the value
        $receiver[$i] = $setter[$i];
    }
}

Upvotes: 1

BeetleJuice
BeetleJuice

Reputation: 40896

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.

Upvotes: 2

splash58
splash58

Reputation: 26153

Function array_splice does what you want

array_splice($receiver, 0, count($setter), $setter);
print_r($receiver);

demo

Upvotes: 1

Related Questions