skip to Main Content

I have 2 arrays
Say Example
A1 = [1,2,3] A2 = [4,5,6]

The output I need is
A3 = [1,4,2,5,3,6]

i.e the output I need is first value of first array followed by first value of second array and so on

How can I achieve this in PHP

I tired some php array functions ,I didn’t get the my required result

2

Answers


  1. Here is a way to do it (assuming that both arrays have the same size):

    function merge($a1, $a2)
    {
        $a3 = [];
        $len = count($a1);
        for($i=0;$i<$len;$i++)
        {
            $a3 []= $a1[$i];
            $a3 []= $a2[$i];
        }
        return $a3;
    }
    
    $a1 = [1, 2, 3];
    $a2 = [4, 5, 6];
    $a3 = merge($a1, $a2);
    var_dump($a3);
    
    Login or Signup to reply.
  2. Maybe you can do something like this:

    $longer_arr = count($arr1) > count($arr2) ? $arr1 : $arr2;
    
    $shorter_arr = count($arr1) > count($arr2) ? $arr2 : $arr1;
    
    $combined_arr = [];
    foreach($longer_arr as $key => $val){
        $combined_arr[] = $val;
        if(isset($shorter_arr[$key])){
            $combined_arr[] = $shorter_arr[$key];
        }
    }
    

    P.s I didn’t tested it

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search