I have three single-dimensional arrays and I need to combine them into one 3-dimensional array where each array in the new array contains one element of each of the three original arrays.
I know how to do this using a simple loop but I was wondering if there is a faster / built-in way of doing this. here is an example of doing this with a loop so you can understand what I’m looking for.
function combineArrays(array $array1, array $array2, array $array3) { //Make sure arrays are of the same size if(count($array1) != count($array2) || count($array2) != count($array3) || count($array1) != count($array3)) { throw new Exception("combineArrays expects all paramters to be arrays of the same length"); } //combine the arrays $newArray = array(); for($count = 0; $count < count($array1); $count++) { $newArray[] = array($array1[$count], $array2[$count], $array3[$count]); } return $newArray; }
Advertisement
Answer
$result = array_map(null,$array1,$array2,$array3);