Content · Web Development · PHP

PHP Arrow Functions

Arrow functions automatically capture outer variables by value in a concise expression. They support one expression, not a full block, and their captured variables are not mutable by.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

Arrow functions automatically capture outer variables by value in a concise expression.

What It Does


Arrow functions automatically capture outer variables by value in a concise expression. The following examples distinguish a normal use case, a boundary case and a practical application.

Requirements and Compatibility


PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.

The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.

Example 1: Basic Behavior


Start with the smallest meaningful working case.

<?php
$prices = [18, 29, 42];
print_r(array_map(fn (int $price): int => $price * 2, $prices));

Example 2: Another Case


Examine the edge case and the observable result.

<?php
$rate = 0.15;
$totals = array_map(fn (float $price): float => round($price * (1 + $rate), 2), [10.0, 20.0]);
print_r($totals);

Practical Example: Putting It to Use


Apply the technique to a small practical task.

<?php
$users = [['active' => true], ['active' => false]];
print_r(array_filter($users, fn (array $user): bool => $user['active']));

Important Behavior and Edge Cases


They support one expression, not a full block, and their captured variables are not mutable by reference.

Comparison with Related Functions or Approaches


OptionWhat it means in practice
Arrow FunctionsArrow functions automatically capture outer variables by value in a concise expression.
Related approachUse a full closure with use (&$variable) when mutable capture is intentional.

Common Beginner Mistakes


MistakeCorrect approach
Ignoring the important boundary for Arrow FunctionsThey support one expression, not a full block, and their captured variables are not mutable by reference.
Assuming a related mechanism has the same behaviorUse a full closure with use (&$variable) when mutable capture is intentional.

Key Takeaways


  • Arrow functions automatically capture outer variables by value in a concise expression.
  • They support one expression, not a full block, and their captured variables are not mutable by reference.
  • Use a full closure with use (&$variable) when mutable capture is intentional.

Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.

Share this resourceSend this page to someone who may find it useful.