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

      Turning User Research Into Real Organizational Change

      July 1, 2025

      June 2025: All AI updates from the past month

      June 30, 2025

      Building a culture that will drive platform engineering success

      June 30, 2025

      Gartner: More than 40% of agentic AI projects will be canceled in the next few years

      June 30, 2025

      I FINALLY got my hands on my most anticipated gaming laptop of 2025 — and it’s a 14-inch monster

      July 1, 2025

      This gimbal-tracking webcam has TWO cameras and a great price — but it may not be “private” enough

      July 1, 2025

      I spent two months using the massive Area-51 gaming rig — both a powerful beast PC and an RGB beauty queen

      July 1, 2025

      “Using AI is no longer optional” — Did Microsoft just make Copilot mandatory for its staff as a critical performance metric?

      July 1, 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

      June report 2025

      July 1, 2025
      Recent

      June report 2025

      July 1, 2025

      Make your JS functions smarter and cleaner with default parameters

      July 1, 2025

      Best Home Interiors in Hyderabad – Top Designers & Affordable Packages

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

      I FINALLY got my hands on my most anticipated gaming laptop of 2025 — and it’s a 14-inch monster

      July 1, 2025
      Recent

      I FINALLY got my hands on my most anticipated gaming laptop of 2025 — and it’s a 14-inch monster

      July 1, 2025

      This gimbal-tracking webcam has TWO cameras and a great price — but it may not be “private” enough

      July 1, 2025

      I spent two months using the massive Area-51 gaming rig — both a powerful beast PC and an RGB beauty queen

      July 1, 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

    CVE-2025-6554 Actively Exploited Google Chrome Zeroday

    July 1, 2025
    Security

    Cyber Brief 25-07 – June 2025

    July 1, 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

    Your Galaxy Watch could get a major sleep apnea upgrade, thanks to AI and Stanford

    News & Updates

    CVE-2025-46672 – NASA CryptoLib Crypto Function Status Validation Bypass

    Common Vulnerabilities and Exposures (CVEs)

    Two Distinct Botnets Exploit Wazuh Server Vulnerability to Launch Mirai-Based Attacks

    Development

    Former head of PlayStation says Microsoft’s Xbox Game Pass is “dangerous” because “big companies dictate what games can be created,” and he could not be more wrong

    News & Updates

    Highlights

    Elastic Grid Scroll: Creating Lag-Based Layout Animations with GSAP ScrollSmoother

    June 3, 2025

    A scroll effect where each column of a grid moves at a slightly different speed,…

    CVE-2025-52568 – NeKernal Memory Corruption Vulnerability

    June 24, 2025

    Beyond cross-functional teams: AI’s radical transformation of agile development

    April 30, 2025

    Gamma AI Platform Abused in Phishing Chain to Spoof Microsoft SharePoint Logins

    April 16, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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