2

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);
3
  • It is mostly the same way as for single values, just loop the second array, then insert the values wherever you want Commented Jan 27, 2020 at 5:39
  • how do u know the position? Commented Jan 27, 2020 at 5:42
  • @TsaiKoga array_1 is final array so I have requirement to print some values by push new item specific position Commented Jan 27, 2020 at 5:44

1 Answer 1

3

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

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

1 Comment

Singh thanks for your great effort answer is exactly as per expectation,I never thought of array_combine I was doing simply using array_splice.

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.