PHP Arrow Functions: Understanding “fn” Syntax

PHP Arrow Functions

Arrow functions were introduced in PHP 7.4. They offer you a way to write simple operations, such as calculations, filters, or maps.

Arrow functions help with simple tasks. You can filter numbers or square values. Also, you can add constants by using fn($n) => $n + 2 inside array functions.

You don’t need to use the use keyword to access outer variables, and you rarely need global inside arrow functions.

Understand How Arrow Functions (fn) Work in PHP

PHP arrow functions give you a shorter way to write simple or repeated functions. You can store them in a variable and call them through that variable.

Here’s the basic syntax:

$func = fn() => VALUES_TO_RETURN;

This syntax uses a short (arrow) function. It skips the function keyword and curly braces. The fn() defines the arrow function, and => returns the value directly—no need to use the return statement.

Arrow functions and traditional anonymous functions both let you create callback functions, but they handle variables from the outer scope differently.

Traditional Anonymous Function:

Here, you must explicitly list external variables with use.

$factor = 2;
$multiply = function ($n) use ($factor) {
    return $n * $factor;
};

echo $multiply(10);

Output:

20

Arrow Function:

It automatically uses variables from the parent scope. No need to use the use keyword.

$factor = 2;
$multiply = fn($n) => $n * $factor;

echo $multiply(30);

Output:

60

Here are the key differences for each one

Arrow functions:

  • They always return the result—no return statement needed.
  • They capture variables by value automatically.

Anonymous functions:

  • You need to use the use (...) keyword to access outer variables.
  • Arrow syntax is shorter.

The main benefit? It lets you write shorter code. For example, when you need a callback function—like with array functions such as array_filter.

Here is an example:

Traditional anonymous function:

$numbers = [1, 2, 3, 4, 5];
$square = array_map(function ($n) {
    return $n * $n;
}, $numbers);

print_r($square );

Output:

Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
)

Arrow function version:

$numbers = [1, 2, 3, 4, 5];
$square = array_map(fn($n) => $n * $n, $numbers);

The output of this example will be the same as the previous one.

Here’s another example that shows how to use array filter numbers fn($n) => $n % 2 === 0:

$numbers = [1, 2, 3, 4, 5];

$even = array_filter($numbers, fn($n) => $n % 2 === 0);

print_r($even);

Output:

Array
(
[1] => 2
[3] => 4
)

This code filters even numbers from an array with an arrow function. Using the fn($n) => $n % 2 === 0 with array_filter is a common arrow function use case.

So, when and why to use them? Let’s answer this question in the following section.

When and Why to Use Arrow Functions in PHP?

Use arrow functions when you do small tasks. They work best in callback functions or simple operations. That happens when you use array functions such as

  • array_map
  • array_filter
  • array_reduce.

Here are why you have to use them:

  • It helps you write short code.
  • No need for use keyword to access global scope variables.
  • Automatic return saves space.
  • It is readable and it has short functions.

When to use them:

  • Inline functions that do one thing.
  • Short logic in closures.
  • Situations where readability matters.
  • Callback functions inside array operations.

Lexical Scoping Clarity

Arrow functions manage scope differently from a traditional anonymous function. Arrow functions copy variables from the parent scope by value automatically instead of the use keyword.

This feature makes the function shorter and easier to write, especially when you do not want to repeat variable names.

This rule is part of what PHP calls lexical scoping. Arrow functions do not have their own scope. They automatically capture variables from the surrounding context by value.

Here is an example:

$multiplier = 10;

$calculate = function ($value) use ($multiplier) {
    return $value * $multiplier;
};

$arrowCalculate = fn($value) => $value * $multiplier;


print_r( $arrowCalculate(55) );

The output:

550

In the first function, you see the use keyword. It tells PHP to bring $multiplier into the function from the outer scope. If you remove use ($multiplier), the function would not know what $multiplier means, and you would get an error.

In the second function, the arrow function skips use. It still accesses $multiplier because arrow functions automatically copy variables from the parent scope. This rule is called lexical scoping.

The arrow function does not create its own scope. It reuses the one from where it was created. The arrow functions only allow one expression. No blocks, no extra lines.

Examples

Print a message with an arrow function:

$uname = "Montasser";
$greet = fn() => "Hello, $uname!";
echo $greet(); 

The arrow function uses a variable from the outer scope ($uname). You don’t need to pass it or use use.

This works because arrow functions automatically inherit from the surrounding scope. It’s useful for short messages or responses.

Discount calculator:

$discount = 15;  
$applyDiscount = fn($price) => $price - ($price * $discount / 100);
echo $applyDiscount(200);  

The 15% is a discount. In this function, we used the $discount from outside. No extra code needed. Arrow functions are good for this kind of logic where you apply a formula.

Here is how to sort with a custom rule:

$names = ["john", "Alice", "bob"];
usort($names, fn($a, $b) => strtolower($a) <=> strtolower($b));
print_r($names); 

The arrow function tells usort how to compare the names. It converts both to lowercase, so sorting ignores case. This keeps the sorting logic short and inside the usort call.

Use in a loop with an external variable:

$bonus = 50;
$salaries = [1000, 1200, 1500];
$withBonus = array_map(fn($salary) => $salary + $bonus, $salaries);
print_r($withBonus);

Arrow function adds the same bonus to each salary. It uses $bonus from outside. No need for use. This shows how arrow functions keep your loop logic cleaner and shorter.

Limitations of Arrow Functions

Arrow functions only support a single expression. They cannot include control structures like if, for, or while, and they do not support multiple statements.

For complex logic, use traditional anonymous functions.

PHP Arrow Function Challenges (Solve These with fn Syntax)

Challenge 1: Multi-Level Array Filter

You are given a 2D array of integers. Filter out subarrays where the sum of elements is less than 100.

$data = [
    [50, 60],
    [30, 20],
    [90, 20]
];

Note: Use array_filter with array_sum inside fn.

Expected output:

[
    [50, 60],
    [90, 20]
]

Your answer:

Challenge 2: Sort by Last Character

Sort an array of words alphabetically based on their last character, using usort and an arrow function.

$words = ['apple', 'banana', 'grape', 'orange'];

Note: This should use fn syntax (arrow function) to sort based on ‘e’, ‘a’, ‘e’, ‘e’.

Expected Output:

[
'banana', // ends with 'a'
'apple', // ends with 'e'
'grape', // ends with 'e'
'orange' // ends with 'e'
]

Your answer:

Challenge 3: Dynamic Tax Calculator

Create a function $addTax = fn($rate) => fn($price) => $price + ($price * $rate); Then apply it to a price list using array_map.

$prices = [100, 250, 75];
$vat = 0.2; // 20%

Note: You should use fn syntax (arrow function) with $addTax to create a closure, then apply it

Expected Output:

[ 120, 300, 90 ]

Your answer:

Wrapping Up

You learned in this tutorial how PHP arrow functions work and how they handle scope without extra setup. You also saw when to use them and how they make your code readable.

Here’s a quick recap:

  • Arrow functions use fn and need only one expression.
  • They inherit variables from the outer scope automatically.
  • You don’t need use or global.
  • They return values without writing return.
  • Avoid them for anything that needs multiple lines or complex logic.

FAQ’s

Can arrow functions replace all anonymous functions?

No. Use arrow functions for short logic only. Use anonymous functions for complex code.

Do arrow functions affect performance?

Not in any significant way. The difference is in readability, not speed.

Can arrow functions have multiple lines?

No. They only support a single expression.

Can arrow functions access global variables?

Yes, they can—just like regular functions. If the global variable is in scope, the arrow function can use it without global.

Can arrow functions be recursive?

Not directly. Since they don’t have a name, they can't call themselves. Use traditional functions for recursion.

Can I use multiple parameters in an arrow function?

Yes. Just separate them with commas:
$sum = fn($a, $b, $c) => $a + $b + $c;

Similar Reads

PHP Integers Guide: Types, Limits, and Conversions

You use integers (int) in PHP to count items, set page numbers, handle IDs, and manage loop counters. In this…

MongoDB PHP Driver: Install and Get Started

Traditional relational databases like MySQL often take center stage. However, with the rise of NoSQL databases, MongoDB has emerged as…

PHP require_once and require

Essentially, “require” and “require_once” are directives in PHP to include and evaluate a specific file during the execution of a…

Inheritance in PHP: Share Code from Class to Class & Examples

PHP developers copied and pasted code across multiple files before inheritance came, which made updates difficult. They updated functions in…

PHP XML Expat Parser: A Complete Guide

If you've ever tried to pull data from an XML file, you know it can be a bit tricky at…

PHP Switch | How the Switch Statement Works in PHP

The PHP switch statement is multiple conditions to only execute one block if its condition generating a true boolean value.…

PHP Strings: Types, Variables & Syntax Tips

If you start working with PHP, it won't take you that long to figure out that strings are everywhere. Besides…

PHP filter_list(): List Available Filters

PHP introduces the filter_list() function to give developers a way to check all available filters in the filter extension. This…

What Is PHP Used For? Meaning of PHP Programming Language

When you first step into web development, one name seems to pop up everywhere: PHP. The PHP programming language has…

PHP array_intersect_key Function: How it Works with Examples

The array_intersect_key in PHP compares arrays by keys and returns only the parts that match. It is useful when you…

Previous Article

PHP filter_var_array: How to Validate Multiple Inputs

Next Article

PHP filter_input: How to Validate Input Securely

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.