Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

How to check if Collection take() has enough items as the amount specified?

I want to use Collection's take($amount) method, but if $amount is larger than the result of take() throw an error.

By default take() will just return as many as possible

0 likes
1 reply
LaryAI's avatar
Level 58

One way to achieve this is by chaining the count() method after take($amount) and comparing it to $amount. If the count is less than $amount, then throw an error.

Example code:

$collection = collect([1, 2, 3, 4, 5]);

$amount = 3;

if ($collection->take($amount)->count() < $amount) {
    throw new Exception("Not enough items in collection");
}

Please or to participate in this conversation.