0

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?

3
  • 2
    Use $data = array_merge($values, $data); Look example: phpize.online/… Commented Dec 15, 2020 at 9:50
  • I am being stupid. It's a great idea. @SlavaRozhnev write it as an answer I will accept this. Commented Dec 15, 2020 at 9:51
  • Probably beneficial to show researchers this related page: stackoverflow.com/q/51250941/2943403 Commented Jul 15, 2021 at 3:33

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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. 

4 Comments

This is identical to the @SlavaRozhnev answer.
I see but when I sees that answer, I already posted mine too. Not an issue the aim is to get a solution.
You still can find a better solution or an alternative solution. This will help other.
This one gets a vote for additionally explaining how array_merge works with the orders

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.