I am trying to create a single array that contains all of the values of an existing multidimensional array. This is what I have so far:
function MaxArray($arr) {
foreach ($arr as $value) {
if (is_array($value)) {
MaxArray($value);
} else {
$array[] = $value;
}
}
print_r($array);
}
$arr = array(array(141,151,161), 2, 3, array(101, 202, array(303,404, array(1,2))));
MaxArray($arr);
When I execute this code, I get this response from the print_r function…
Array ( [0] => 141 [1] => 151 [2] => 161 ) Array ( [0] => 1 [1] => 2 ) Array ( [0] => 303 [1] => 404 ) Array ( [0] => 101 [1] => 202 ) Array ( [0] => 2 [1] => 3 )
As you can see, this is not what I am looking for and I can’t figure out how to combine all of the values in the multidimensional array into a single array. Can anyone please point me in the right direction here?
What you’re trying to do is often called ‘array flattening’, so
ArrayFlattenis probably a better name for a function thanMaxArray(since the latter sounds like it’ll return the highest value in the array, whichmaxdoes very well).ArrayFlattencould be written like this:And used like this:
To get this:
Array ( [0] => a [1] => b [2] => x [3] => y [4] => z [5] => p )From here.