Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6418

Inserting multiple values from an array using array_unshift() method

array_unshift is using for inserting one or many values at the beginning of an array. Now I have an array-

$data = [1, 3, 4];

Another array is needed to insert at the beginning of the $data array.

$values = [5, 6];

Here I want to insert the values 5, 6 at the beginning of the $data array, and the resulting $data would be-

$data = [5, 6, 1, 3, 4];

Note: I know there is a way like array_unshift($data, ...$values); but this is working from php7.3.x AFAIK. I need to do it below php7.3.

Is there any way to do this without looping the $values array in the reverse order?

Upvotes: 0

Views: 963

Answers (2)

Nads
Nads

Reputation: 109

You should use array_merge instead of array_unshift.

$data = [1, 3, 4];
$values = [5, 6];

$result = array_merge($values, $data); // the sequence of the array inside array_merge will decide which array should be merged at the beginning. 

Upvotes: 2

Slava Rozhnev
Slava Rozhnev

Reputation: 10163

Function array_merge exists since PHP 4:

<?php
$data = [1, 3, 4];

$values = [5, 6];

$data = array_merge($values, $data);

print_r($data);

Live PHP sandbox

Upvotes: 2

Related Questions