Power Tools: Arrow Functions & Array Helpers
9 min · PHP
Write compact arrow functions and transform arrays with array_map and array_filter.
Enemy 1 of 5
Arrow functions: a shorthand for small functions
An arrow function is a compact, one-line shorthand for defining a small function: fn($params) => expression. Two things make it different from a regular function() declaration: it automatically captures variables from the surrounding scope (a regular function normally can't see outside variables unless you explicitly import them with the `use` keyword), and it has an implicit return — whatever the expression evaluates to is automatically handed back, with no return keyword required.
Arrow functions are especially handy for short, throwaway logic that you're going to pass straight into another function — like a one-off comparison or transformation — rather than something you'll want to call by name from many places. If the logic needs more than a single expression, a regular function() is usually the better, more readable choice.
Loading editor...