Using SPL recursive iterators

The Standard PHP Library SPL has many built-in iterators for recursion purposes. We can use them as per our need, without taking the pain of implementing them from scratch. Here is the list of iterators and their functionality:

  • RecursiveArrayIterator: This recursive iterator allows iterating over any type of array or objects and modifying the key or values or unsetting them. It also allows iterating over the current iterator entry.

  • RecursiveCallbackFilterIterator: If we are looking forward to applying a callback recursively to any array or objects, this iterator can be very helpful.

  • RecursiveDirectoryIterator: This iterator allows iterating any directory or filing systems. It makes the directory listing very easy. For example, we can rewrite the directory listing program we wrote in this chapter easily using this iterator:

$path = realpath('.'); 

$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $name => $file) {
echo "$name ";
}
  • RecursiveFilterIterator: If we are looking for a filter option in our iteration recursively, we can use this abstract iterator to implement the filtering part.

  • RecursiveIteratorIterator: If we want to iterate over any recursive iterator, we can use this one. It is already built-in, and we can easily apply it. An example of how it is used is shown in the directory iterator section in the RecursiveDirectoryIterator section.

  • RecursiveRegexIterator: If you want to apply a regular expression to filter an iterator, we can use this iterator along with other iterators.

  • RecursiveTreeIterator: The recursive tree iterator allows us to create a graphical representation like a tree for any directory or multidimensional array. For example, the following football team list array will produce a tree structure:

$teams = array( 
'Popular Football Teams',
array(
'La Lega',
array('Real Madrid', 'FC Barcelona', 'Athletico Madrid', 'Real
Betis', 'Osasuna')
),
array(
'English Premier League',
array('Manchester United', 'Liverpool', 'Manchester City', 'Arsenal',
'Chelsea')
)
);


$tree = new RecursiveTreeIterator(
new RecursiveArrayIterator($teams), null, null, RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($tree as $leaf)
echo $leaf . PHP_EOL;

The output will look like this:

|-Popular Football Teams
| |-La Lega
| |-Real Madrid
| |-FC Barcelona
| |-Athletico Madrid
| |-Real Betis
| -Osasuna
|-English Premier League
|-Manchester United
|-Liverpool
|-Manchester City
|-Arsenal
-Chelsea
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset