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?

Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
  • 2
    Use `$data = array_merge($values, $data);` Look example: https://phpize.online/?phpses=439eab6d7d3b11ffa1827608f95f1ae0&sqlses=null&php_version=php5&sql_version=mysql57 – Slava Rozhnev Dec 15 '20 at 09:50
  • I am being stupid. It's a great idea. @SlavaRozhnev write it as an answer I will accept this. – Sajeeb Ahamed Dec 15 '20 at 09:51
  • Probably beneficial to show researchers this related page: https://stackoverflow.com/q/51250941/2943403 – mickmackusa Jul 15 '21 at 03:33

2 Answers2

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
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. 
Nads
  • 109
  • 9