Laravel Collections: flip() for Instant Lookups

📖 1 minute read

Here’s a Laravel Collection performance trick: use flip() to turn expensive searches into instant lookups.

I was looping through a date range, checking if each date existed in a collection. Using contains() works, but it’s O(n) for each check — if you have 100 dates to check against 50 items, that’s 5,000 comparisons.

// Slow: O(n) per check
$available = collect(['2026-01-25', '2026-01-26', '2026-01-27']);
if ($available->contains($date)) { ... }

The fix — flip() converts values to keys, making lookups O(1):

// Fast: O(1) per check
$available = collect(['2026-01-25', '2026-01-26'])
    ->flip(); // Now: ['2026-01-25' => 0, '2026-01-26' => 1]

if ($available->has($date)) { ... }

For small datasets, the difference is negligible. But checking hundreds or thousands of items? This tiny change saves significant processing time. Costs nothing to implement.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *