Introduction
Arrow Functions and Callback Functions in PHP help you write cleaner, shorter, and reusable PHP code. Arrow functions simplify anonymous functions, while callbacks allow you to pass functions as arguments. In this chapter, you will learn both concepts through 10 practical solved PHP examples.
Question 1: Create a Simple Arrow Function to Display a Welcome Message
Problem Statement
Create an arrow function that accepts a student’s name and returns a welcome message.
PHP Solution
<?php
$welcome = fn($name) => "Welcome to PHP, " . $name;
echo $welcome("Rahul");
?>
Sample Output
Welcome to PHP, Rahul
Explanation
fnis the keyword used to create an arrow function.$nameis the function parameter.- The arrow function returns the welcome message automatically.
$welcome("Rahul")calls the function.
Concepts Covered
- Arrow functions
- Function parameters
- Automatic return values
Question 2: Calculate Total Salary Using an Arrow Function
Problem Statement
Create an arrow function that accepts an employee’s basic salary and allowance and returns the total salary.
PHP Solution
<?php
$totalSalary = fn($basic, $allowance) => $basic + $allowance;
echo "Total Salary: " . $totalSalary(25000, 5000);
?>
Sample Output
Total Salary: 30000
Explanation
The arrow function accepts two parameters and adds them together. When we pass ₹25,000 as basic salary and ₹5,000 as allowance, it returns ₹30,000.
Concepts Covered
- Multiple parameters
- Arrow function calculations
- Returning values
Question 3: Calculate Discounted Product Price Using an Arrow Function
Problem Statement
A shop offers a 10% discount on a product. Create an arrow function that accepts the original price and returns the discounted price.
PHP Solution
<?php
$discountPrice = fn($price) => $price - ($price * 10 / 100);
echo "Discounted Price: " . $discountPrice(2000);
?>
Sample Output
Discounted Price: 1800
Explanation
The arrow function calculates 10% of the original price and subtracts the discount from it.
For a product costing ₹2,000, the discount is ₹200. Therefore, the final price is ₹1,800.
Concepts Covered
- Arrow functions
- Percentage calculations
- Returning calculated values
Question 4: Increase Product Prices Using array_map()
Problem Statement
You have an array of product prices. Use an arrow function with array_map() to increase every product price by 10%.
PHP Solution
<?php
$prices = [1000, 2000, 3000, 4000];
$updatedPrices = array_map(
fn($price) => $price + ($price * 10 / 100),
$prices
);
print_r($updatedPrices);
?>
Sample Output
Array
(
[0] => 1100
[1] => 2200
[2] => 3300
[3] => 4400
)
Explanation
array_map()applies a callback to every element.- The arrow function receives each product price.
- It increases the price by 10%.
- The updated prices are stored in a new array.
Concepts Covered
- Arrow functions
- Callback functions
array_map()- Array transformation
Question 5: Filter Passing Students Using array_filter()
Problem Statement
You have an array of student marks. Use an arrow function with array_filter() to display only students who scored 40 or more marks.
PHP Solution
<?php
$marks = [85, 32, 67, 25, 90, 45];
$passedStudents = array_filter(
$marks,
fn($mark) => $mark >= 40
);
print_r($passedStudents);
?>
Sample Output
Array
(
[0] => 85
[2] => 67
[4] => 90
[5] => 45
)
Explanation
array_filter()checks each array element using a callback.- The arrow function checks whether each mark is at least 40.
- Only matching marks are included in the result.
- Original array keys are preserved.
Concepts Covered
- Arrow functions
- Callback functions
array_filter()- Array filtering
Question 6: Sort Product Prices Using a Callback Function
Problem Statement
You have an array of product prices. Use usort() with an arrow function callback to sort the prices from lowest to highest.
PHP Solution
<?php
$prices = [4500, 1200, 3500, 800, 2500];
usort($prices, fn($a, $b) => $a <=> $b);
print_r($prices);
?>
Sample Output
Array
(
[0] => 800
[1] => 1200
[2] => 2500
[3] => 3500
[4] => 4500
)
Explanation
usort()sorts an array using a custom comparison callback.- The arrow function compares two values at a time.
- The spaceship operator (
<=>) returns a comparison result. - The array is sorted in ascending order.
usort()reindexes the array keys.
Concepts Covered
- Callback functions
- Arrow functions
usort()- Spaceship operator
Question 7: Create a Custom Function That Accepts a Callback
Problem Statement
Create a function named calculateResult() that accepts two numbers and a callback function. Use the callback to calculate their sum.
PHP Solution
<?php
function calculateResult($a, $b, $callback) {
return $callback($a, $b);
}
$result = calculateResult(
20,
30,
fn($x, $y) => $x + $y
);
echo "Result: " . $result;
?>
Sample Output
Result: 50
Explanation
calculateResult()accepts two numbers and a callback.- The callback is received through the
$callbackparameter. $callback($a, $b)executes the supplied function.- The arrow function adds the two numbers and returns the result.
Concepts Covered
- Custom callback functions
- Arrow functions
- Passing functions as arguments
- Function execution
Question 8: Use a Named Function as a Callback
Problem Statement
Create a named function called calculateSquare() that returns the square of a number. Pass this function to array_map() to calculate the square of every number in an array.
PHP Solution
<?php
function calculateSquare($number) {
return $number * $number;
}
$numbers = [2, 4, 6, 8];
$squares = array_map("calculateSquare", $numbers);
print_r($squares);
?>
Sample Output
Array
(
[0] => 4
[1] => 16
[2] => 36
[3] => 64
)
Explanation
calculateSquare()is a named function.- Its name is passed to
array_map()as a callback. array_map()calls this function for every array element.- The returned square values are stored in
$squares.
Concepts Covered
- Named functions
- Callback functions
array_map()- Array transformation
Question 9: Calculate Employee Bonuses Using an Arrow Function
Problem Statement
An organization gives employees a bonus equal to 10% of their salary. Use an arrow function with array_map() to calculate the bonus for every employee.
PHP Solution
<?php
$employees = [
["name" => "Rahul", "salary" => 30000],
["name" => "Priya", "salary" => 40000],
["name" => "Amit", "salary" => 50000]
];
$employeeBonuses = array_map(
fn($employee) => [
"name" => $employee["name"],
"salary" => $employee["salary"],
"bonus" => $employee["salary"] * 10 / 100
],
$employees
);
print_r($employeeBonuses);
?>
Sample Output
Array
(
[0] => Array
(
[name] => Rahul
[salary] => 30000
[bonus] => 3000
)
[1] => Array
(
[name] => Priya
[salary] => 40000
[bonus] => 4000
)
[2] => Array
(
[name] => Amit
[salary] => 50000
[bonus] => 5000
)
)
Explanation
- The
$employeesarray stores employee names and salaries. array_map()processes each employee record.- The arrow function calculates 10% of the employee’s salary.
- It returns a new array containing the employee name, salary, and bonus.
Concepts Covered
- Arrow functions
- Callback functions
- Multidimensional arrays
array_map()- Employee bonus calculations
Question 10: Build an Employee Salary Report Using Arrow and Callback Functions
Problem Statement
You have employee salary records. Increase each employee’s salary by ₹5,000 using an arrow function and array_map(). Then use array_filter() with another arrow function to display only employees whose updated salary is ₹35,000 or more.
PHP Solution
<?php
$employees = [
["name" => "Rahul", "salary" => 25000],
["name" => "Priya", "salary" => 32000],
["name" => "Amit", "salary" => 40000],
["name" => "Neha", "salary" => 28000]
];
$updatedEmployees = array_map(
fn($employee) => [
"name" => $employee["name"],
"salary" => $employee["salary"] + 5000
],
$employees
);
$selectedEmployees = array_filter(
$updatedEmployees,
fn($employee) => $employee["salary"] >= 35000
);
print_r($selectedEmployees);
?>
Sample Output
Array
(
[1] => Array
(
[name] => Priya
[salary] => 37000
)
[2] => Array
(
[name] => Amit
[salary] => 45000
)
)
Explanation
- The
$employeesarray stores the original employee records. array_map()increases every employee’s salary by ₹5,000.- The updated records are stored in
$updatedEmployees. array_filter()checks the updated salary of each employee.- Only employees earning ₹35,000 or more are included in the final report.
- Original array keys are preserved by
array_filter().
Concepts Covered
- Arrow functions
- Callback functions
array_map()array_filter()- Multidimensional arrays
- Employee salary reports
Key Takeaways
- Arrow functions provide a shorter way to write anonymous functions.
- Arrow functions use the
fnkeyword. - Arrow functions automatically capture variables from the parent scope by value.
- Arrow functions contain a single expression and return its result automatically.
- Callback functions allow one function to be passed into another function.
- Named functions and anonymous functions can both be used as callbacks.
array_map()applies a callback to array elements.array_filter()selects array elements based on a callback condition.usort()uses a callback to define custom sorting rules.- Custom PHP functions can also accept callbacks as arguments.
Frequently Asked Questions (FAQs)
1. What is an arrow function in PHP?
An arrow function is a shorter way to write an anonymous function using the fn keyword. It automatically returns the result of its single expression.
2. What is the syntax of an arrow function in PHP?
fn($parameter) => expression;
3. What is a callback function in PHP?
A callback is a function passed as an argument to another function so that it can be executed when needed.
4. What is the difference between arrow functions and anonymous functions?
Arrow functions use the fn keyword and automatically capture variables from the parent scope by value. Traditional anonymous functions use the function keyword and can capture variables explicitly using use.
5. Can arrow functions accept multiple parameters?
Yes. Arrow functions can accept multiple parameters.
$add = fn($a, $b) => $a + $b;
echo $add(10, 20);
Output:
30
6. Can arrow functions use variables from outside their scope?
Yes. Arrow functions automatically capture variables from the parent scope by value.
7. Can arrow functions be used with array_map()?
Yes. Arrow functions can be passed to array_map() to perform operations on every element of an array.
8. Can arrow functions be used with array_filter()?
Yes. They can be used with array_filter() to select array elements that satisfy a condition.
9. Can a named function be used as a callback?
Yes. You can pass the function name as a string or callable to another function.
10. Which PHP version supports arrow functions?
Arrow functions were introduced in PHP 7.4. You need PHP 7.4 or later to use them.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
