search

Home  >  Q&A  >  body text

The way to merge two arrays is to alternate the first value in PHP

<p>I have 2 array examples A1 = [1,2,3], A2 = [4,5,6]</p><p>The output I need is A3 = [1,4, 2,5,3,6]</p><p>That is, the output I need is the first value of the first array, followed by the first value of the second array, and so on </p><p>How can I implement this functionality in PHP? </p><p>I tried some PHP array functions but didn't get the results I wanted</p><p><br /></p>
P粉288069045P粉288069045492 days ago533

reply all(1)I'll reply

  • P粉155710425

    P粉1557104252023-08-09 13:10:17

    Here is one way to do this (assuming both arrays are of 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);

    reply
    0
  • Cancelreply