Symfony Doctrine PHP ArrayCollection class: 15 Code Examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

PHP ArrayCollection is an instance of the Doctrine Collection interface. It is an OOP variant of the native PHP array. This article explains Doctrine and Collection interface. There are many examples of different Collection methods as well.

Using Symfony Doctrine ArrayCollection

An array is a fundamental data structure known for keeping data in contiguous memory space. Almost every programming language has an array built in at its core.

A regular PHP array is unique in the sense that essentially, they are maps, having key and value pairs.

There are tons of articles about PHP arrays and the relevant functions at FuelingPHP. Arrays are highly usable and helpful for persisting multiple entities, but there are some scenarios where native PHP arrays can be hectic to deal with. A typical scenario is data persistence and mapping to and from a database.

Array PHP and OOP

Databases come in many shapes and flavors. But looking at the bigger picture, there are SQL and No-SQL databases. SQL databases are more structured and tabular, while No-SQL doesn’t care much about structure but focuses on storage and performance. Nonetheless, these databases interact in an Object-Oriented fashion, meaning that they expect objects for persistence and mapping.

Now, PHP arrays don’t exhibit the OOP patterns.

All the functions relevant to native PHP arrays are not an object’s methods. Objects are more powerful and extendable, and there could be tons of easily callable methods. Therefore, the OOP pattern opens up a way for easily interacting with an underlying database.

One way to use an array in an OOP fashion is decorating it in a wrapper, a class, or an interface that makes it an object with all the OOP superpowers.

Luckily, a library is out there that does the same thing.

Doctrine ArrayCollection

Doctrine is an open-source project that includes PHP libraries focused on dealing with databases – persistence and mapping.

It has many cool projects, including Collection, that we’ll be exploring here. Collection is an interface, essentially a wrapper for native PHP array representation. PHP ArrayCollection is an instance of Collection.

Think of PHP ArrayCollection as a more extended form of PHP arrays. Many methods are readily available on Doctrine ArrayCollection, making it OOP-based, thus flexible and easy to use.

PHP ArrayCollection includes many methods to add, modify and manipulate entities. Let’s begin exploring it through examples.

Let’s see how to install Doctrine Collection in the first place. 

Installing Doctrine ArrayCollection

Doctrine is an open-source project available on Github. It is not a built-in PHP library, and that’s why it has to be installed explicitly. For that, PHP requires composer, a package manager that does all the hard work for you. You can download it from composer official website. Follow the instructions and set up composer.

Once you’ve composer setup, proceed to the terminal and run the following command.

composer require doctrine/collections

This command downloads and installs doctrine collection and thus makes it available for use.

Instantiating ArrayCollection

So here’s an example of how to instantiate a PHP ArrayCollection object.

<?php
require __DIR__ . '/vendor/autoload.php';
 
use Doctrine\Common\Collections\ArrayCollection;
 
$collection = new ArrayCollection(['Anna', 'Brad', 'Drake']);
 
print_r($collection)
?>

The first two lines are necessary to include Doctrine Collection. The new ArrayCollection instantiates the new collection, an ArrayCollection of strings here.

So, let’s jump to the methods straight.

#1 – Doctrine ArrayCollection add method

Here’s how to add an element to the end of an ArrayCollection.

$collection->add('Franklin'); //['Anna', 'Brad', 'Drake', 'Franklin']

See that the collection invokes the methods in an OOP way, this is different than adding elements to an array with array_push.

#2 – Doctrine ArrayCollection remove method

Here’s how to remove an element by index.

$collection->remove(0); //['Brad', 'Drake', 'Franklin']

It removes the element at index 0, the first element.

#3 – Doctrine ArrayCollection remove element method

$collection->removeElement('Drake'); //['Brad', 'Franklin']

It looks for the element and removes it if exists.

#4 – ArrayCollection exists method

$collection->exists(function($key, $value) {
    return $value === 'Brad';
}); // true

The exists method takes a function with two arguments, key and value. It returns true based on a boolean condition as shown in the example.

#5 – Doctrine ArrayCollection getValues method

$collection->getValues(); //['Brad', 'Franklin']

This is similar to the array_values function.

#6 – Doctrine ArrayCollection getKeys method

$collection->getKeys(); //[0, 1]

This is similar to the array_keys function.

#7 –  ArrayCollection contains method

$collection->contains('Susi'); // false

 It looks for a value in the array and returns true if exists or false otherwise. 

#8 –  ArrayCollection containsKey method

$contains = $collection->containsKey(0); // true

Look, we can check if the collection contains not only the value but also the key. This looks for a key in the array and returns true if exists else it will return false

#9 –  Doctrine ArrayCollection clear method

$collection->clear();

It unsets the array.

#10 –  ArrayCollection isEmpty method

$collection->isEmpty(); //true

If the collection has no elements then this method returns true.

Phew! Lots of methods. These are not all infact. There are many other methods listed in the official documentation. So, if you’re curious you can read about these methods.

Using the Internal iterator position

One of the coolest things we can do with the ArrayCollection class is to loop through the items in a standard object-oriented fashion. You can loop through the collection using standard foreach loops. It’ll use the getIterator() function which retrieves the current iterator position.

This will expose the internal iterator for you to fulfill complex looping requirements.

Get the Next Element in the Collection

ArrayCollection has a neat next function that allows you to get the next element in the collection. It takes the current iterator position and retrieves the adjacent element for the given element.

<?php 

$collection->next();

Get the Last Element in the Collection

You can also return the last element in a collection with the following given function.

<?php

$collection->last();

Get the Index of a Value in the Collection

Use the ArrayCollection indexOf function to get the array index based on the value. This useful function checks both the value and type. This means reference equality has been achieved.

I find this function really useful whenever I need to check whether the value exists and where are the keys of the elements returned. If it doesn’t contain the value then it will return false.

Using PHP Arrays in an OOP Way with ArrayCollection

This article introduces Doctrine, an open-source project about database storage and object mapping. Doctrine has numerous projects, including Collection, an interface that wraps the PHP native array in a class, giving it OOP capabilities. PHP ArrayCollections are a lot easier to work with and include numerous useful methods. 

So hopefully, you’ve learned something new today about PHP. If you’re determined to learn more, check PHP articles and tutorials at FuelingPHP

Learn More on Symfony

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.