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 Variadic Functions: Use Unlimited Arguments

PHP Variadic functions show you a way to handle a variable number of arguments within a function. They are designed…

PHP Comparison Operators Guide with Examples

PHP comparison operators allow you to compare values in many ways, and this simplifies the process of checking whether values…

PHP array_diff_ukey Function: How it Works with Examples

The PHP array_diff_ukey function compares keys in two or more arrays. It returns the keys from the first array that…

PHP List MongoDB Collections

Sometimes, you may need to list collections with MongoDB in a PHP environment to manage or analyze your database structure.…

PHP array_fill_keys: Create Arrays with Specific Keys

The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…

PHP filter_var: Understand How to Sanitize Input

PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used…

PHP strtolower Function: Convert Strings to Lowercase

Text does not always look the same. One word may appear in lowercase, another in uppercase. You want both to…

OOP Interface PHP: How to Set Rules for Classes

PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…

PHP Object | How to Create an Instance of a Class

The PHP object is an instance from the PHP class or the main data structure that is already been created…

PHP Ternary Operator: How to Write Short Expressions

The PHP ternary operator gives you a way to write short expressions. It reduces lines of code and avoids long…

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.