Menu

Type-safe collections in PHP 8.4: what I wish arrays had
📰

Type-safe collections in PHP 8.4: what I wish arrays had

DEV Community·delacry·7 months ago
#FZ295HMQ
#php#symfony#laravel#webdev#user
Reading 0:00
15s threshold

You know the feeling. You're three callbacks deep in array_map , you tack on array_filter , then array_values to fix the keys, and PhpStorm gives up and types everything as array . PHPStan was useful five lines ago. Now it's just nodding politely.

I spent six months of weekends building a library to fix this. It's called noctud/collection , it's PHP 8.4+ only, and this post is about why.

The everyday pain

Here's a scene that probably looks familiar:

$activeAdmins = array_values ( array_filter ( array_map ( fn ( $u ) => $u -> refresh (), $users ), fn ( $u ) => $u -> isActive () && $u -> isAdmin () ) );

Enter fullscreen mode

Exit fullscreen mode

Three problems packed into one expression.

Read order fights execution order. Your eyes hit array_values first, but it runs last. You parse the code in the opposite direction it executes, every time, forever.

Types collapse. array_filter returns array<int, User> . array_values returns array<int, User> .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.