🔄 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 :
Share

🔄 PHP Object Iteration

Or Copy Link

CONTENTS
Scroll to Top