Home > Article > Backend Development > PHP uses recursive algorithm to traverse an array infinitely
The example in this article describes PHP's use of recursive algorithm to infinitely traverse the array. Share it with everyone for your reference, the details are as follows:
<?php //无限遍历数组 $a1 = array("a", "b", "c"); //一维数组 $a2 = array(array(21, 3, 6), array("a", "b", "c")); //二维数组 $a3 = array(array(array(5, 55), 4, 444), 2, 7, 6, 8, array("w", "d", array(3, 2, "a"), "s")); //多维不规则数组 function fun($a) { foreach ($a as $val) { if (is_array($val)) { //如果键值是数组,则进行函数递归调用 fun($val); } else { // 如果键值是数值,则进行输出 echo "$val<br />"; } //end if } //end foreach } //end fun //fun($a1); //fun($a2); fun($a3); ?>
Output:
5 55 4 444 2 7 6 8 w d 3 2 a s
I hope this article will be helpful to everyone in PHP programming.
For more related articles on examples of PHP using recursive algorithm to infinitely traverse arrays, please pay attention to the PHP Chinese website!