Discover how a tiny syntax change can make your PHP code cleaner and faster to write!
Why Arrow functions (short closures) in PHP? - Purpose & Use Cases
Imagine you want to quickly create a small function inside another function to process some data, like filtering or mapping an array. You write a full function with all the usual syntax, even though it's just a tiny task.
Writing full functions for small tasks takes extra lines, makes your code bulky, and harder to read. It's easy to make mistakes copying variables or forgetting to return values. This slows you down and makes your code messy.
Arrow functions let you write tiny functions in one line, capturing variables automatically. This makes your code shorter, cleaner, and easier to understand at a glance.
$result = array_map(function($x) use ($factor) { return $x * $factor; }, $numbers);$result = array_map(fn($x) => $x * $factor, $numbers);
You can write quick, clear, and concise functions inside other functions without extra clutter or mistakes.
When processing a list of prices to apply a discount, arrow functions let you write the calculation in one short line, making your code neat and easy to update.
Manual small functions are long and error-prone.
Arrow functions shorten code and auto-capture variables.
They make your code cleaner and faster to write.