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

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 9, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 9, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 9, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 9, 2025

      Your password manager is under attack, and this new threat makes it worse: How to defend yourself

      May 9, 2025

      EcoFlow’s new backyard solar energy system starts at $599 – no installation crews or permits needed

      May 9, 2025

      Why Sonos’ cheapest smart speaker is one of my favorites – even a year after its release

      May 9, 2025

      7 productivity gadgets I can’t live without (and why they make such a big difference)

      May 9, 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

      Tap into Your PHP Potential with Free Projects at PHPGurukul

      May 9, 2025
      Recent

      Tap into Your PHP Potential with Free Projects at PHPGurukul

      May 9, 2025

      Preparing for AI? Here’s How PIM Gets Your Data in Shape

      May 9, 2025

      A Closer Look at the AI Assistant of Oracle Analytics

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

      kew v3.2.0 improves internet radio support and more

      May 9, 2025
      Recent

      kew v3.2.0 improves internet radio support and more

      May 9, 2025

      GNOME Replace Totem Video Player with Showtime

      May 9, 2025

      Placemark is a web-based tool for geospatial data

      May 9, 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:

    FeatureArrow FunctionAnonymous Function
    Introduced inPHP 7.4PHP 5.3
    SyntaxShort, single-expressionVerbose, full-function body
    Scope handlingAutomatic (lexical)Manual (use) keyword
    Multiline bodyNot allowedAllowed
    Return keywordNot usedRequired

    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

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 9, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2024-13962 – Avast Cleanup Premium Link Following Local Privilege Escalation Vulnerability

    May 9, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Distribution Release: T2 SDE 25.4

    News & Updates

    Pinot is a real-time analytics platform

    Linux

    Specs and prices for Acer’s new AI PC gaming handhelds have been revealed — They’re a lot heftier than I expected

    News & Updates

    Overwatch 2’s Perk system radically changes how the game is played

    News & Updates
    Hostinger

    Highlights

    From Product to Cart: Adding Guiding Animations to the Shopping Experience

    November 21, 2024

    An in-depth tutorial on how to create an engaging animation where items move from the…

    MIT engineers grow “high-rise” 3D chips

    December 20, 2024

    Lara Ozkan named 2025 Marshall Scholar

    December 20, 2024

    The evolving landscape of data privacy: Key trends to shape 2025

    January 24, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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