PHPBuilder - Using SPL Iterators in PHP to Interact with Different Data Types



RSS Twitter
Articles Php Functions

Using SPL Iterators in PHP to Interact with Different Data Types

by: W. Jason Gilmore
|
March 16, 2011

Although PHP was originally conceived as a procedural language, object-oriented features have been incorporated into every major release going all the way back to version 3. Offering a compliment of features such as interfaces, namespaces, and inheritance, developers hailing from other object-oriented languages such as Java and C++ can quickly adapt to PHP with little trouble.
Indeed, object-oriented programming (OOP) has become so pervasive within the PHP community that many choose to employ the approach at every opportunity. One great way to incorporate more OOP into your applications is through the Standard PHP Library (SPL), a powerful yet largely unknown extension made part of the official PHP language with the PHP 5.0 release. The SPL provides a series of classes which extend the PHP language in numerous ways, offering object-oriented advanced data structures, iterators, and file handlers, among other features.
In this tutorial I'll introduce you to several of my favorite SPL iterators, providing you with the basis from which you can continue your own exploration. Following several examples, I'll conclude with a brief introduction to other key SPL features.

Introducing SPL Iterators (in PHP 5)

The SPL provides over 20 classes useful for iterating over and manipulating different types of data, including arrays, directories, files, and XML. For instance the ArrayIterator class is useful for interacting with arrays. Consider for instance the following array:
$platforms = array('Nintendo DS', 'PlayStation 2', 'PlayStation 3');
You can use the ArrayIterator class to work with the $platforms array in a strictly object-oriented fashion:
$platforms = array('Nintendo DS', 'PlayStation 2', 'PlayStation 3');

// Load the array into an array object
$platformArray = new ArrayObject($platforms);

// Append a new platform to the end of the array
$platformArray->append('Xbox 360');

// Determine the array size
printf("Tracking %d platforms:
", $platformArray->count()); // Iterate over the array, outputting each array element for($i = $platformArray->getIterator(); $i->valid(); $i->next()) { printf("%s
", $i->current()); }
Executing this snippet produces the following output:
Tracking 4 platforms:
Nintendo DS
PlayStation 2
PlayStation 3
Xbox 360

Iterating Over a Filesystem Directory with DirectoryIterator

Several recent projects have involved interaction with the server's file system, including using PHP to learn more about how many images reside in a specific directory. You can use the SPL's DirectoryIterator class to easily navigate a directory, to learn more about the files, file permissions, and file owners, among other things. Consider a directory named images, which contains the following five images: house.png, icon.gif, logo.jpg, truck.png and vacation.png. The following snippet can be used to parse this directory in order to determine how many different file types exist:
<!--p

$extensions = array();

// Iterate over a directory named images
foreach (new DirectoryIterator('images') as $fileInfo) {

  // If the iterator is placed atop . or .., continue
  if($fileInf-->isDot()) continue;
    
  // Use the pathinfo() function to parse the file name
  $file = pathinfo($fileInfo->getFilename());

  // We only want the file extension
  $extension = $file['extension'];

  // Determine if the extension name is already being tracked
  // in the $extensions array. If so, increment the associated
  // value. Otherwise, add the extension to the array.
  if (array_key_exists($extension, $extensions))
  {
    $extensions[$extension]++;
  } else {
    $extensions[$extension] = 1;
  }

}

var_dump($extensions);

?>
Executing this snippet produces the following results (formatted for readability):
array
 'png' => int 3
 'gif' => int 1
 'jpg' => int 1

1
|
2
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
W. Jason Gilmore

Comment:



Comment:

(Maximum characters: 1200). You have characters left.