0
0
PhpConceptBeginner · 3 min read

Arrow Function in PHP: What It Is and How to Use It

An arrow function in PHP is a short syntax for anonymous functions introduced in PHP 7.4 that allows writing functions in a concise way using the => operator. It automatically captures variables from the surrounding scope without needing the use keyword.
⚙️

How It Works

Think of an arrow function as a quick way to write a small function without all the usual extra words. Instead of writing a full function with curly braces and a return statement, you use a simple arrow => to say what the function should return.

It’s like giving a short instruction directly, and PHP understands it immediately. Also, arrow functions automatically grab any variables from the outside world that they need, so you don’t have to tell them explicitly.

This makes your code cleaner and easier to read, especially when you want to pass a small function as a value, like when sorting or filtering lists.

💻

Example

This example shows how to use an arrow function to double each number in an array. It’s shorter and clearer than a regular anonymous function.

php
<?php
$numbers = [1, 2, 3, 4];
$doubled = array_map(fn($n) => $n * 2, $numbers);
print_r($doubled);
?>
Output
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
🎯

When to Use

Use arrow functions when you need a quick, simple function without extra code. They are perfect for small tasks like transforming or filtering data, especially inside functions like array_map, array_filter, or sorting functions.

They help keep your code short and readable, making it easier to understand what the function does at a glance. However, for complex functions with multiple statements, use regular functions instead.

Key Points

  • Arrow functions use the fn keyword and the => syntax.
  • They automatically capture variables from the surrounding scope.
  • They always return the result of the expression after the arrow.
  • Best for short, simple functions with one expression.
  • Introduced in PHP 7.4 for cleaner, more concise code.

Key Takeaways

Arrow functions provide a concise way to write simple anonymous functions in PHP.
They automatically capture variables from the surrounding scope without needing 'use'.
Use arrow functions for short, single-expression functions to keep code clean.
For complex logic, prefer regular anonymous functions with full syntax.
Arrow functions were introduced in PHP 7.4 and use the 'fn' keyword with '=>'.