Home >Backend Development >PHP Tutorial >Recursively traverse PHP multidimensional array_PHP tutorial
Array traversal is a common programming task in PHP, and arrays are divided into one-dimensional arrays, two-dimensional arrays and multi-dimensional arrays. Traversing a one-dimensional array is very simple and can be completed with a for loop. So how should the traversal of two-dimensional arrays and multi-dimensional arrays be implemented? Please see the following procedure:
<?php /* * ------------------------------------------------- * Author : bkjia * Url : www.bkjia.com * Date : 2011-03-09 * ------------------------------------------------- */ function arr_foreach ($arr) { if (!is_array ($arr)) { return false; } foreach ($arr as $key => $val ) { if (is_array ($val)) { arr_foreach ($val); } else { echo $val.'<br/>'; } } } $arr1 = array (1=>array(11,12,13,14=>array(141,142)),2,3,4,5); echo '<pre class="brush:php;toolbar:false">'; print_r($arr1); echo '<pre class="brush:php;toolbar:false">'; arr_foreach ($arr1); ?>
The result of running the program is:
Array ( [1] => Array ( [0] => 11 [1] => 12 [2] => 13 [14] => Array ( [0] => 141 [1] => 142 ) ) [2] => 2 [3] => 3 [4] => 4 [5] => 5 ) 11 12 13 141 142 2 3 4 5
The program is very simple, you can see the wonderful use of recursion in it.