Quantcast
Channel: Lil Josh » PHP
Viewing all articles
Browse latest Browse all 11

Recursion in PHP

$
0
0

Using recursion can be a little hard to grasp if you are new to the concept. In it’s simplest form it’s a function that calls upon itself to create a loop. It is commonly used for traversing tree structures. This example shows PHP using recursion to get a list of all the child pages under a folder structure.

<?php

function getPages($folder, $pages=array()) {
  //function returns everything in the folder 1 level
  $assets = getChildren($folder); 

  foreach($assets as $asset) {
    if($asset->type == 'folder') {
      $pages = getPages($asset->path, $pages);
    } else if ($asset->type == 'page') {
      array_push($pages, $asset->name);
    }
  }

  return $pages;
}

?>

recursion


Viewing all articles
Browse latest Browse all 11

Trending Articles