Search code examples
phparraysarray-pusharray-splice

How to push array elemnt to specific position in another array using php


I want to push new array to another array at specific position for this purpose I used array_splice followed some stackoverflow links but it didn't work for me

I refered this links also but they mentioned only for single value not array.

How to insert element into arrays at specific position?

Insert new item in array on any position in PHP

Example:

$array_1 = array(1,2,3,4,5);

$array_2 = array(a,b,c);

Now I want to push $array_2 values in $array_1 at certain position like:

a at position 1

b at position 3

c at position 4

Expected output:

$final_array=(1,a,2,b,c,3,4,5);

Solution

  • You need to define positions as array and combine it with array_2. Now iterate over this combined array and use code of first reference thread:

    <?php
    
    $array_1 = array(1,2,3,4,5);
    $array_2 = array('a','b','c');
    
    //define positions array
    $positions = array(1,3,4);
    
    //combine position array with $array_2
    $positionArray = array_combine($positions, $array_2);
    
    //iterate over combined array
    foreach($positionArray as $key => $value){
        //use code of first example thread
        array_splice($array_1, $key, 0, $value);
        //here $key is position where you want to insert
    }
    
    print_r($array_1);
    

    Output: https://3v4l.org/Djar2