PHP, combine two arrays into a new array [closed]

Sounds to me like you’re looking for array_merge, or array_merge_recursive

Perhaps a better fit would be:

$result = array();
for($i=0, $j= count($arr1);$i<$j;$i++)
{//standard loop over array
    $result[$i] = array_merge($arr1[$i], $arr2[$i]);
}

That should give you what you need. But please, do look into various array_* functions, there’s 79 of them in total, odds are that there is one out there, or rather in the core, that suites your needs.

The closest I can get to your desired result, without being too silly is this:

$result = array();
for($i=0, $j= count($arr1);$i<$j;$i++)
{//standard loop over array
    unset($arr2[$i][3]);
    $arr2[$i] = array_filter($arr2[$i], 'is_string');//gets rid of all the numbers
    $result[$i] = array_unique(array_merge($arr1[$i], $arr2[$i]));
}

This outputs:

array(2) {
  [0]=>
  array(4) {
    [0]=>
    string(1) "a"
    [1]=>
    string(2) "1a"
    [2]=>
    string(7) "Aye Aye"
    [3]=>
    string(6) "Female"
  }
  [1]=>
  array(4) {
    [0]=>
    string(1) "b"
    [1]=>
    string(2) "2b"
    [2]=>
    string(5) "Mg Mg"
    [3]=>
    string(4) "Male"
  }
}

Leave a Comment