0
0
PHPprogramming~5 mins

Arrow functions (short closures) in PHP

Choose your learning style9 modes available
Introduction
Arrow functions let you write small functions quickly and clearly without extra words.
When you need a quick function inside another function.
When you want to keep your code short and easy to read.
When you want to use variables from outside the function without extra code.
When you write simple one-line functions for things like sorting or filtering.
Syntax
PHP
fn (argument_list) => expression;
Arrow functions always return the result of the expression automatically.
They can use variables from the outside without needing the 'use' keyword.
Examples
A simple arrow function that doubles a number.
PHP
$double = fn($x) => $x * 2;
An arrow function that adds two numbers.
PHP
$sum = fn($a, $b) => $a + $b;
An arrow function that returns a greeting message.
PHP
$greet = fn($name) => "Hello, $name!";
Sample Program
This program uses an arrow function to double each number in the array and prints the new array.
PHP
<?php
$numbers = [1, 2, 3, 4];
$double = fn($x) => $x * 2;
$doubledNumbers = array_map($double, $numbers);
print_r($doubledNumbers);
OutputSuccess
Important Notes
Arrow functions are always one expression and return its value automatically.
They are shorter and cleaner than regular anonymous functions for simple tasks.
Arrow functions inherit variables from the parent scope automatically.
Summary
Arrow functions provide a short way to write simple functions.
They automatically return the result of their expression.
They can use outside variables without extra syntax.