Search code examples
phparraysarraylisttransposeflatten

Push elements from two arrays in an alternating fashion to form a new flat array


I need a function that can intersect 2 arrays for example:

$Array1 = array(1,2,3);
$Array2 = array(5,6);

and results in:

array(1,5,2,6,3);

What I have so far is this

<?php
$Array1 = array(1,2,3);
$Array2 = array(5,6);

function zip() {
    $args = func_get_args();
    $zipped = array();
    $n = count($args);
    for ($i=0; $i<$n; ++$i) {
        reset($args[$i]);
    }
    while ($n) {
        $tmp = array();
        for ($i=0; $i<$n; ++$i) {
            if (key($args[$i]) === null) {
                break 2;
            }
            $tmp[] = current($args[$i]);
            next($args[$i]);
        }
        $zipped[] = $tmp;
    }
    return $zipped;
}

$bothMonths = zip($Array1, $Array2);

print_r($bothMonths);

?>

that have the output like

Array (
    [0] => Array (
        [0] => 1
        [1] => 5
    )
    [1] => Array (
        [0] => 2
        [1] => 6
    )
)

I don't know why 3 is missing.

Also I need pure programming, forget about array_merge, array_intersect ... or other functions.


Solution

  • Try this:

    function custom_intersect($arr1, $arr2) {
       $len1 = count($arr1);
       $len2 = count($arr2);
       $max_len = ($len1 >= $len2) ? $len1 : $len2;
    
       $arr = array();
       for($i = 0; $i < $max_len; ++$i)
       {
          if(isset($arr1[$i]))
          {
             $arr[] = $arr1[$i];
          }
          if(isset($arr2[$i]))
          {
             $arr[] = $arr2[$i];
          }
       }
       return $arr;
    }