How to combine two arrays into one and three arrays into one in PHP

I found a nice snippet for combining two arrays into one. I’d love to credit the original source, but unfortunately I can’t remember it and I can’t seem to find it in Google anymore. If you are the original author or know who they are, please let me know so I can credit accordingly.

Here is the code for combining two arrays into one:

<?php

function array_combine($arr1, $arr2) {
$out = array();

$arr1 = array_values($arr1);
$arr2 = array_values($arr2);

foreach($arr1 as $key1 => $value1) {
$out[(string)$value1] = $arr2[$key1];
}

return $out;
}

?>

That’s all well and good, but I had three arrays that I needed to combine into one. So I modified the above code to come up with this, it combines three arrays into one multidimensional array:

<?php

function double_array_combine($arr1, $arr2, $arr3) {
$out = array();

$arr1 = array_values($arr1);
$arr2 = array_values($arr2);
$arr3 = array_values($arr3);

foreach($arr1 as $key1 => $value1) {
$out[(string)$value1][0] = $arr2[$key1];
$out[(string)$value1][1] = $arr3[$key1];
}

return $out;
}?>

So that’s pretty simple. If you want to combine four arrays into one and so on, just add more arrays to the code according to the above example. So how do you use these functions? Well, let’s say you have these three arrays: $name, $address, $phone. You want to combine the three into one array. Just include the above code in your script, and then use this script to call the function:

<?php

$new_array=double_array_combine($name, $address, $phone);

print_r($new_array); // this will print out the contents of your new array

?>