Recursive multidimensional array traversing


/ Published in: PHP
Save to your folder(s)

Traverses a multidimensional array and returns an array with the results. It also echoes the result as a string just for demonstration.


Copy this code and paste it in your HTML
  1. function array_traverse($arr)
  2. {
  3. static $recursive_array = array(); // Static to mantain state when doing recursive function
  4.  
  5. // Traverse array, if a value is an array do recursive call to traverse that array
  6. foreach($arr as $value)
  7. {
  8. if(is_array($value))
  9. {
  10. array_traverse($value);
  11. }
  12. else
  13. {
  14. $recursive_array[] = $value;
  15. echo $value."<br />\n";
  16. }
  17. }
  18.  
  19. return $recursive_array;
  20. }
  21.  
  22. $arr = array(1, array(141,151,161), 2, 3, 5, array(101, 202, array(303,404)));
  23.  
  24. var_dump(array_traverse($arr));

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.