๐Ÿ”„ PHP Object Iteration โ€“ Loop Through Object Properties Easily

Learn how to iterate over PHP objects using foreach, how to implement the Iterator interface, and how to customize iteration for advanced use cases.


๐Ÿงฒ Introduction โ€“ Why Iterate Over Objects?

In PHP, object iteration allows you to loop through object properties just like arrays. This is useful when you want to process dynamic object data, build JSON responses, filter results, or create iterable models.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to loop over public object properties with foreach
  • How to customize object iteration using interfaces
  • How to implement Iterator or IteratorAggregate
  • Best practices for clean and flexible object iteration

๐Ÿ” 1. Basic Object Iteration with foreach

class User {
    public $name = "Alice";
    public $email = "alice@example.com";
}

$user = new User();

foreach ($user as $key => $value) {
    echo "$key: $value<br>";
}

โžก๏ธ By default, PHP allows foreach to loop over public properties only.
โžก๏ธ private and protected properties are not accessible this way.


๐Ÿšซ 2. Iteration and Visibility

class Product {
    private $id = 1;
    public $name = "Laptop";
}

$product = new Product();

foreach ($product as $key => $value) {
    echo "$key: $value<br>"; // Outputs only 'name'
}

โžก๏ธ Only public properties are visible during iteration.
โžก๏ธ Use interfaces to customize iteration logic.


๐Ÿงฉ 3. Custom Iteration with IteratorAggregate

class Collection implements IteratorAggregate {
    private $items = ["one", "two", "three"];

    public function getIterator(): Traversable {
        return new ArrayIterator($this->items);
    }
}

$collection = new Collection();

foreach ($collection as $item) {
    echo $item . "<br>";
}

โžก๏ธ IteratorAggregate requires you to implement getIterator()
โžก๏ธ Returns any Traversable object, like ArrayIterator


๐Ÿ”„ 4. Full Control with Iterator Interface

class Numbers implements Iterator {
    private $numbers = [10, 20, 30];
    private $index = 0;

    public function current() {
        return $this->numbers[$this->index];
    }

    public function key() {
        return $this->index;
    }

    public function next() {
        $this->index++;
    }

    public function rewind() {
        $this->index = 0;
    }

    public function valid() {
        return isset($this->numbers[$this->index]);
    }
}

$nums = new Numbers();

foreach ($nums as $num) {
    echo $num . "<br>";
}

โžก๏ธ Iterator gives you full control over iteration behavior.
โžก๏ธ Implement all 5 methods for complete functionality.


๐Ÿง  Best Practices

  • โœ… Use IteratorAggregate for simple wrapper classes
  • โœ… Use Iterator when you need full control over the internal pointer
  • โœ… Always return a Traversable from getIterator()
  • โŒ Donโ€™t expose private data unless intentionally iterated
  • โœ… Use SPL iterators (ArrayIterator, DirectoryIterator) when possible

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Object iteration in PHP is powerful and customizable. From simple property loops to advanced class iteration using interfaces, PHP provides everything you need to iterate cleanly and efficiently.

๐Ÿ” Key Takeaways:

  • foreach loops over public properties by default
  • Implement IteratorAggregate or Iterator for custom logic
  • Use built-in iterators for flexible and reusable code

โš™๏ธ Real-World Use Cases:
Form field collections, data models, file directories, custom API response objects, service containers


โ“ Frequently Asked Questions (FAQs)

โ“ Can I iterate private properties with foreach?
โŒ No. Use Iterator or IteratorAggregate to expose them selectively.

โ“ Whatโ€™s the difference between Iterator and IteratorAggregate?
โœ… Iterator gives full control; IteratorAggregate is simpler and returns a traversable object.

โ“ Can I return an array from getIterator()?
โŒ No. You must return a Traversable like ArrayIterator.

โ“ Can I modify the object during iteration?
๐Ÿ”ธ Yes, but be careful โ€” modifying properties while looping can cause unpredictable behavior.

โ“ Are SPL iterators better than writing custom iterators?
โœ… In most cases, yes. Use built-in iterators unless you need custom logic.


Share Now :

Leave a Reply

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

Share

๐Ÿ”„ PHP Object Iteration

Or Copy Link

CONTENTS
Scroll to Top