• About Us
    • New York
  • Work
  • Capabilities
  • Careers
  • Technology
  • Blog
  • Contact Us
  • About Us
    • New York
  • Work
  • Capabilities
  • Careers
  • Technology
  • Blog
  • Contact Us
January 26, 2016

Generators & Iterator Aggregate: A Match Made in PHP Heaven

Posted by Christopher Davis

iterator-aggregate-generator

PHP added generators in version 5.5. You see them in code with the yield keyword and they tend to be used most often to iterate over a collection dynamically without creating it in memory all at once. Really you can do all sorts of fun things with generators that we’re not going to touch here.

IteratorAggregate has been around forever — since PHP 5.0. It’s a way to make an object traversable (able to be used in a foreach loop) without having to implement all the methods of Iterator. IteratorAggregate also makes it possible to do nested loops on the same object.

A powerful combination is to use a generator within your IteratorAggregate::getIterator implementation. Rather than returning a new iterator object each time, just supply a generator. Here’s a small example.

And it’s usage:

This is an extremely powerful pattern when you need to iterate over collections with some form of known computation mixed in. Our recently released CSV library does this to produce associative arrays from a CSV file.

Something more dynamic would be better suited to a generic map implementation.

PHP
Previous
Next

Latest White Papers

  • Shifting Plans for 2020 & Beyond
  • Game On: How Brands Can Log Into A Diverse Multi-Billion Dollar Industry
  • What CCPA Means For Brands
  • How Google is Improving Consumer Data Privacy
  • Ways to Prepare for the Cookieless Future
  • See all White Papers

Featured Posts

  • Ad Age Names PMG #1 Best Place to Work in 2021
  • Hindsight 2020 & Looking Ahead to 2021
  • Preparing for Streaming’s Growth & The Future of TV Buying
  • MediaPost Names PMG Independent Agency of the Year
  • PMG Client Portfolio Trends During Amazon Prime Day 2020

Categories

  • Consumer Insights
  • Content
  • Creative Design
  • Data Analytics
  • Development
  • Digital TV & Video
  • Ecommerce
  • Industry News
  • Local
  • Mobile
  • Paid Search
  • PMG Culture
  • Programmatic & Display
  • SEO
  • Social Media
  • Structured Data
Fort Worth

2845 West 7th Street
Fort Worth, TX 76107

Dallas

3102 Oak Lawn Avenue
Suite 650
Dallas, TX 75219

Austin

823 Congress Avenue
Suite 800
Austin, TX 78701

London

33 Broadwick Street
London
W1F 0DQ

New York

120 East 23rd Street
New York, NY 10010

Get in touch

(817) 420 9970
info@pmg.com

Subscribe to the PMG Newsletter
© 2021 PMG Worldwide, LLC, All Rights Reserved
  • Contact
  • Privacy Policy
 Tweet
 Share
 Tweet
 Share
 Tweet
 Share
 LinkedIn
We and our partners use cookies to personalize content, analyze traffic, and deliver ads. By using our website, you agree to the use of cookies as described in our Cookie Policy.