Horje Website
PHP Recursive Function – Learn Recursive function – PHP Code

PHP Recursive Function – Learn Recursive function

PHP Recursive Function - Learn Recursive function - PHP Code


 
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>PHP Recursive Function</title>
  5. </head>
  6. <body>
  7. <?php
  8. // Defining recursive function
  9. function printValues($arr) {
  10. global $count;
  11. global $items;
  12. // Check input is an array
  13. if(!is_array($arr)){
  14. die("ERROR: Input is not an array");
  15. }
  16. /*
  17. Loop through array, if value is itself an array recursively call the function,
  18. else add the value found to the output items array,
  19. and increment counter by 1 for each value found
  20. */
  21. foreach($arr as $a){
  22. if(is_array($a)){
  23. printValues($a);
  24. } else{
  25. $items[] = $a;
  26. $count++;
  27. }
  28. }
  29. // Return total count and values found in array
  30. return array('total' => $count, 'values' => $items);
  31. }
  32. // Define nested array
  33. $species = array(
  34. "birds" => array(
  35. "Eagle",
  36. "Parrot",
  37. "Swan"
  38. ),
  39. "mammals" => array(
  40. "Human",
  41. "cat" => array(
  42. "Lion",
  43. "Tiger",
  44. "Jaguar"
  45. ),
  46. "Elephant",
  47. "Monkey"
  48. ),
  49. "reptiles" => array(
  50. "snake" => array(
  51. "Cobra" => array(
  52. "King Cobra",
  53. "Egyptian cobra"
  54. ),
  55. "Viper",
  56. "Anaconda"
  57. ),
  58. "Crocodile",
  59. "Dinosaur" => array(
  60. "T-rex",
  61. "Alamosaurus"
  62. )
  63. )
  64. );
  65. // Count and print values in nested array
  66. $result = printValues($species);
  67. echo $result['total'] . ' value(s) found: ';
  68. echo implode(', ', $result['values']);
  69. ?>
  70. </body>
  71. </html>



Try Your Self ->



Published:
September 25, 2020
Author:
admin
Category:
PHP Basic, PHP Source Code
Views:
16

This article was posted in PHP Basic, PHP Source Code and tagged , , . Bookmark the permalink. Follow comments with the RSS feed for this post.Post a Comment or leave a trackback: Trackback URL.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Horje © 2011 - 2023