Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Agent Mode for Gemini added to Android Studio

      June 24, 2025

      Google’s Agent2Agent protocol finds new home at the Linux Foundation

      June 23, 2025

      Decoding The SVG path Element: Curve And Arc Commands

      June 23, 2025

      This week in AI dev tools: Gemini 2.5 Pro and Flash GA, GitHub Copilot Spaces, and more (June 20, 2025)

      June 20, 2025

      Microsoft is reportedly planning yet more major cuts at Xbox — as early as next week

      June 24, 2025

      Microsoft makes Windows 10 security updates FREE for an extra year — but there’s a catch, and you might not like it

      June 24, 2025

      “Deus Ex” just turned 25 years old and it’s still the best PC game of all time — you only need $2 to play it on practically anything

      June 24, 2025

      Where to buy a Meta Quest 3S Xbox Edition — and why it’s a better bargain than the “normal” Meta Quest 3S

      June 24, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Vite 7.0 Is Out

      June 24, 2025
      Recent

      Vite 7.0 Is Out

      June 24, 2025

      Exploring JavaScript ES2025 Edition

      June 24, 2025

      Mastering Mixed DML Operations in Apex

      June 24, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft is reportedly planning yet more major cuts at Xbox — as early as next week

      June 24, 2025
      Recent

      Microsoft is reportedly planning yet more major cuts at Xbox — as early as next week

      June 24, 2025

      Microsoft makes Windows 10 security updates FREE for an extra year — but there’s a catch, and you might not like it

      June 24, 2025

      “Deus Ex” just turned 25 years old and it’s still the best PC game of all time — you only need $2 to play it on practically anything

      June 24, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Use Arrow Functions in PHP 7.4+

    How to Use Arrow Functions in PHP 7.4+

    May 9, 2025

    Arrow functions were introduced in PHP 7.4 to allow devs to write short, anonymous functions. They offer a compact alternative to traditional closures, especially when the function body is small and focused.

    In this article, you will learn how to use the arrow function in PHP with examples. You’ll also learn about the difference between arrow functions and anonymous functions.

    Table of Contents

    • Prerequisites

    • Understand the Arrow Functions in PHP

    • The Difference Between Arrow Functions and Anonymous Functions in PHP

      • 1. Syntax

      • 2. Variable Scope (Lexical Scope)

      • 3. Readability and Brevity

    • How to Return Arrow Functions from Other Functions

    • How to Use Arrow Functions in Your Code?

      • Use the Arrow Function within array_map()

      • Use the Arrow Function with array_filter()

      • Use the arrow function with array_reduce()

      • Nest arrow functions in PHP

    • Wrapping Up

    Prerequisites

    You should know how to write basic PHP code, such as functions, and be able to work with arrays. Make sure you’re using PHP 7.4 or newer because arrow functions only work in that version and above.

    Understanding Arrow Functions in PHP

    The PHP arrow function is a shorthand syntax. It defines an anonymous function and is designed for simple operations and expressions.

    Arrow functions in PHP are best used when:

    • You need a quick callback or inline function.

    • The function returns a single expression.

    • You want to avoid repetitive use statements.

    The basic syntax of an arrow function is:

    fn(parameter_list) => expression;
    
    • fn is the keyword that defines the arrow function.

    • parameter_list is the list of parameters (similar to a normal function).

    • => separates the parameter list from the expression.

    • expression is the value the function returns. You cannot use a block of statements here – only a single expression is allowed.

    Arrow functions automatically capture variables from the scope. They don’t need the use keyword as shown below:

    $var_name = 10; 
    $func = function($n) use ( $var_name ) {
       return $n * $var_name;
    }
    

    You can use the variables in the scope directly:

    $var_name = 10; 
    $func = fn($n) => $n * $var_name;
    

    Here’s a lexical scoping example:

    $multiplier = 3;
    $multiply = fn($x) => $x * $multiplier;
    echo $multiply(4); // Outputs: 12
    

    The variable $multiplier is automatically captured from the outer scope. You don’t need to use use($multiplier) as you would in a traditional anonymous function.

    Key rules of arrow function syntax:

    • Always use fn, not function.

    • No curly braces or return keyword – just a single expression.

    • Automatic variable capture from the outer scope.

    • It cannot contain multiple statements or control structures (like if, foreach, and so on).

    Let’s move on to the following section to take a look at the difference between arrow functions and anonymous functions in PHP.

    The Difference Between Arrow Functions and Anonymous Functions in PHP

    PHP supports two types of anonymous functions (that is, functions without a name):

    • Traditional anonymous functions are defined by the function keyword

    • Arrow functions are introduced in PHP 7.4 within the fn keyword

    Both types can be assigned to variables and used for callbacks or as function arguments. They serve similar purposes, but differ in syntax and how they handle external variables.

    Let’s look at their key differences.

    1. Syntax

    Arrow Function:

    Arrow functions use a single-line expression without braces or a return statement.

    $square = fn($n) => $n * $n;
    

    The arrow function assigns it to the variable $square. The function takes one parameter, $n, and returns $n * $n (the square of $n).

    Anonymous Function:

    $square = function($n) {
        return $n * $n;
    };
    

    Anonymous functions use a full function block and require an explicit return. They’re used for multi-line logic or complex behavior.

    2. Variable Scope (Lexical Scope)

    Arrow functions automatically capture variables from the outer scope:

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

    Anonymous functions require you to manually import external variables using use:

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

    You cannot use the variable in the scope within the anonymous function unless you use the use keyword.

    3. Readability and Brevity

    Arrow functions are shorter. They help you write small and single-expression callbacks:

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

    But anonymous functions are better when:

    • The function body has multiple lines.

    • You need complex logic or control structures.

    Here is a table that shows you the key differences:

    Feature Arrow Function Anonymous Function
    Introduced in PHP 7.4 PHP 5.3
    Syntax Short, single-expression Verbose, full-function body
    Scope handling Automatic (lexical) Manual (use) keyword
    Multiline body Not allowed Allowed
    Return keyword Not used Required

    Let’s move on to the section below to understand how to return an arrow function from another function.

    How to Return Arrow Functions from Other Functions

    Functions are first-class citizens. This means you can return a function from another function. That includes arrow functions.

    You can define and return an arrow function from within a regular function like this:

    function getMultiplier($factor) {
        return fn($x) => $x * $factor;
    }
    
    $double = getMultiplier(2);
    echo $double(5); // Outputs: 10
    

    In this example:

    • getMultiplier() returns an arrow function.

    • The arrow function captures $factor from the outer scope automatically (lexical scoping).

    • The returned function can be stored in a variable and used like any other callable.

    It lets you generate small functions based on parameters and reduces code repetition.

    Use this syntax when you need to build dynamic behavior – like custom filters or function factories.

    Let’s move on to the section below to see how you can use arrow functions in your code.

    How to Use Arrow Functions in Your Code

    Use the Arrow Function within array_map():

    array_map() lets you set a callback to each element of an array. It allows you to define the callback directly within the function call.

    Example:

    $numbers = [1, 2, 3, 4, 5];
    
    $squares = array_map(fn($n) => $n * $n, $numbers);
    
    print_r($squares);
    // Outputs: [1, 4, 9, 16, 25]
    

    The arrow function fn($n) => $n * $n is executed for each element of the $numbers array. The result is a new array of squared values.

    Use the Arrow Function with array_filter()

    array_filter() filters elements of an array within a callback. Arrow functions define a short filter condition inline.

    Example:

    $numbers = [1, 2, 3, 4, 5, 6];
    
    $evenNumbers = array_filter($numbers, fn($n) => $n % 2 === 0);
    
    print_r($evenNumbers);
    // Outputs: [2, 4, 6]
    

    Here, the arrow function checks if each number is even. The result is an array that contains only the even numbers.

    Use the arrow function with array_reduce()

    array_reduce() reduces an array to a single value based on a callback function. Arrow functions help make the code compact.

    Example:

    $numbers = [1, 2, 3, 4, 5];
    
    $sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
    
    echo $sum; // Outputs: 15
    

    The arrow function adds each number in the array. $carry holds the running total and $n is the current number.

    Nest arrow functions in PHP

    Here the inner function performs one operation and the outer function processes the results of the inner function.

    $numbers = [1, 2, 3, 4, 5];
    
    $doubleAndSquare = array_map(
        fn($n) => fn($x) => ($x * 2) ** 2,  
        $numbers
    );
    
    $results = array_map(
        fn($fn) => $fn(3),  
        $doubleAndSquare
    );
    
    print_r($results);
    // Outputs: [36, 36, 36, 36, 36]
    

    In the above code, the first array_map() creates a list of arrow functions that double and then square the number. Each element in the $numbers array gets mapped to a nested arrow function.

    The second array_map() applies the inner arrow function (which doubles and squares the value) to the number 3. It results in an array of the same result.

    Wrapping Up

    In this article, you’ve learned the basic features and syntax of arrow functions. It shows you their advantages over anonymous functions.

    Here are some key takeaways:

    1. Arrow functions were introduced in PHP 7.4. They provide you with a new syntax to define anonymous functions with simpler code.

    2. Arrow functions are a shorter way to write anonymous functions. They use one line of code and don’t need curly braces or the return keyword.

    3. Arrow functions automatically get variables from scope. This allows you to use an arrow function as a callback in functions like array_map() or array_filter().

    Resources:

    • PHP docs on arrow functions

    • Flatcoding blog where I publish many other tutorials

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticlePrepare for your iOS interview
    Next Article Free GenAI 65-Hour Bootcamp

    Related Posts

    Security

    Rogue WordPress Plugin Unmasked: Stealthy Malware Skims Credit Cards & Steals Credentials

    June 24, 2025
    Security

    Urgent Advantech Alert: Critical Flaws (CVSS 9.6) Expose Industrial Automation to Remote Takeover, PoC Releases

    June 24, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-2069 – FileZ Cross-Site Scripting (XSS)

    Common Vulnerabilities and Exposures (CVEs)
    Ahold Delhaize USA Confirms Data Stolen in 2024 Cyberattack

    Ahold Delhaize USA Confirms Data Stolen in 2024 Cyberattack

    Development

    CVE-2025-4459 – Code-projects Patient Record Management System SQL Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)
    Learn Lynx to Create JavaScript Mobile Apps

    Learn Lynx to Create JavaScript Mobile Apps

    Development

    Highlights

    Grabber is an imageboard/booru downloader

    May 11, 2025

    Grabber is an imageboard/booru downloader which can download thousands of images from multiple boorus very…

    Iconic adds images on top of a folder icon

    June 11, 2025

    Microsoft will force updates for Teams clients released over 90 days ago

    April 10, 2025

    CVE-2025-6274 – WebAssembly wabt Resource Consumption Vulnerability

    June 19, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.