What Is a Collection in PHP? (Beginner Guide)

A collection is a special class. It usually has helper methods like: count(), first(), filter(), map() etc. It is designed to be iterable.

If you’re learning MVC or ORMs in PHP, you’ll often see code like:

$members = Member::all();

foreach ($members as $member) {
    echo $member->name;
}

And the confusion starts:

  • What is $members?
  • Is “collection” a new PHP datatype?
  • Why not just use arrays?

Let’s simplify it 👇


Collection is NOT a PHP datatype

PHP has no built-in “collection” type.

A collection is simply:

👉 a normal PHP class that wraps an array and is iterable

That’s it.


Why collections exist

Collections are used when:

  • You have multiple objects
  • You want to loop over them
  • You want helpful methods like:
    • count()
    • first()
    • filter()

Instead of working with raw arrays, collections give cleaner and safer code.


Model vs Collection (important)

Model (single item)

$member = Member::find(1);
echo $member->name;
  • Represents one database row
  • ❌ Not iterable
  • ❌ No foreach

Collection (multiple items)

$members = Member::all();

foreach ($members as $member) {
    echo $member->name;
}
  • Holds many Member objects
  • ✅ Iterable
  • ✅ Designed for looping

A very small collection example

class MemberCollection implements IteratorAggregate
{
    private array $items;

    public function __construct(array $items)
    {
        $this->items = $items;
    }

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

    public function first()
    {
        return $this->items[0] ?? null;
    }
}

Usage:

$members = new MemberCollection([
    new Member(),
    new Member()
]);

foreach ($members as $member) {
    // works
}

$firstMember = $members->first();

Why not make models iterable?

Because it doesn’t make sense.

  • A Member is one thing
  • A Collection is many things

Good design keeps them separate.


Key takeaway 🧠

  • ❌ Collection is not a PHP feature
  • ✅ It’s a class
  • ✅ It wraps an array of objects
  • ✅ It makes iteration and data handling easier
  • ✅ Models = single item, Collections = many items

Once this clicks, MVC and ORMs feel much simpler 👍