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

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

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

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

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

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

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

    Development

    GPT-5 is Coming: Revolutionizing Software Testing

    July 22, 2025
    Development

    Win the Accessibility Game: Combining AI with Human Judgment

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

    Welcome to Manga Office

    Artificial Intelligence

    US indicts Black Kingdom ransomware admin for Microsoft Exchange attacks

    Security

    Laravel Too Many Login Attempts: Restrict and Customize

    Development

    OpenBMB Releases MiniCPM4: Ultra-Efficient Language Models for Edge Devices with Sparse Attention and Fast Inference

    Machine Learning

    Highlights

    CVE-2025-4671 – WordPress Profile Builder Stored Cross-Site Scripting Vulnerability

    June 3, 2025

    CVE ID : CVE-2025-4671

    Published : June 3, 2025, 12:15 p.m. | 3 hours, 14 minutes ago

    Description : The Profile Builder plugin for WordPress is vulnerable to Stored Cross-Site Scripting via the plugin’s user_meta and compare shortcodes in all versions up to, and including, 3.13.8 due to insufficient input sanitization and output escaping on user supplied attributes. This makes it possible for authenticated attackers, with contributor-level access and above, to inject arbitrary web scripts in pages that will execute whenever a user accesses an injected page.

    Severity: 6.4 | MEDIUM

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    Microsoft Surface PC prices drop at Best Buy for a limited time — up to $500 off new models and $1,000 off refurbs

    June 20, 2025

    Load up your Kindle for summer: Get up to 93% off popular eBooks at Amazon right now

    April 24, 2025

    HazyBeacon: Novel Backdoor Uses AWS Lambda for Stealthy C2, Targets Govts

    July 15, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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