Check if ArrayCollection is empty
Asked Answered
T

2

32

I have an Entity Order which hold Suppliers in an Arraycollection. In my controller i want to check if this arraycollection is empty:

$suppliers = $order->getSuppliers();

I tried:

if(!($suppliers)) {}
if(empty($suppliers)) {}

Any ideas?

Tinatinamou answered 14/7, 2013 at 19:44 Comment(0)
D
96

Doctrine ArrayCollection has a method isEmpty that will do what you are looking for.

if ($suppliers->isEmpty()) { }

Take a look at the documentation for it here

Dilettante answered 14/7, 2013 at 19:52 Comment(4)
Note: This is preferable over count() == 0. doctrine-project.org/api/common/2.3/…Azikiwe
Yes, and you are bond to Doctrine (for ever) :-/Biogenesis
@UrosMajeric - not really, you would just need to ensure that your concrete methods (or your own interface) matched the Collection interface if you migrated away from Doctrine.Dilettante
In addition to what @KenHannel said, one could also add Order::hasSuppliers(): bool method, which returns $this->suppliers->isEmpty(). This way, if someday you decide to migrate from Doctrine, you will need to change your code in only one place.Antigen
O
7

You can also use the count() PHP function:

if (count($suppliers) < 1) { }
Oates answered 17/12, 2014 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.