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


$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:




You need to definepositions as array and combine it witharray_2. Now iterate over this combined array and use code of first reference thread:


$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



People are also looking for solutions to the problem: php - Doctrine: owning side and inverse side


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.