Search code examples
phparraysarray-merge

Creating new array from existing arrays in php


I'm trying to create a new array containing values from pre-existing arrays.

<?php

$array1 = array(
    0 => 101,
    1 => 102,
    2 => 121,
    3 => 231,
    4 => 232,
    5 => 233
);

$array2 = array(
    0 => 58,
    1 => 98,
    2 => 45,
    3 => 48,
    4 => 45,
    5 => 85
);

$result = array();

Notice that the first element is from $array1, second element from $array2 and so on.

Any pointer is highly appreciated.


Solution

  • Example of how you can achieve this:

        $array = array(4,5,6);
        $array2 = array(8,9,0,12,44,);
        $count1 = count($array);
        $count2 = count($array2);
        $count = ($count1 > $count2) ? $count1 : $count2;
        $rez = array();
        for ($i = 0; $i < $count; $i++) {
            if ($i < $count1) {
               $rez[] = $array[$i];
            } 
            if ($i < $count2) {
               $rez[] = $array2[$i];
            }
    
    
        }
    
    var_dump($rez);
    

    Result will be an array

    array(8) {
      [0]=>
      int(4)
      [1]=>
      int(8)
      [2]=>
      int(5)
      [3]=>
      int(9)
      [4]=>
      int(6)
      [5]=>
      int(0)
      [6]=>
      int(12)
      [7]=>
      int(44)
    }
    

    but if you need to save empty values you can remove this checks if ($i < $count2)