What are the advantages of using a Collection Class over a simple array for storing objects in PHP?

Using a Collection Class over a simple array in PHP offers several advantages, such as providing additional methods for manipulating and accessing the data, better type safety, and encapsulation of the data structure. Collection classes can also offer better performance for certain operations, such as filtering or mapping elements.

class Collection {
    private $items = [];

    public function add($item) {
        $this->items[] = $item;
    }

    public function remove($index) {
        unset($this->items[$index]);
    }

    public function get($index) {
        return $this->items[$index];
    }

    public function count() {
        return count($this->items);
    }
}

// Example usage
$collection = new Collection();
$collection->add("Item 1");
$collection->add("Item 2");
$collection->remove(0);
echo $collection->get(0); // Output: Item 2
echo $collection->count(); // Output: 1