Anonymous Functions and Closures in PHP Solved Practice Questions with Solutions

Introduction

Anonymous Functions and Closures in PHP allow you to create functions without giving them a name and store them in variables. They are useful for performing specific tasks, handling callbacks, and working with arrays. In this tutorial, you will practise anonymous functions, closures, variable capturing, and the use keyword through solved PHP practice questions with simple examples and solutions.

Question 1: Create a Simple Anonymous Function

Problem Statement:
Create an anonymous function that displays a welcome message. Store the function in a variable named $welcome and execute it.

PHP Solution:

<?php
$welcome = function() {
    echo "Welcome to PHP Programming!";
};

$welcome();
?>

Sample Output:

Welcome to PHP Programming!

Explanation:

  • An anonymous function is a function without a declared name.
  • The function is stored in the $welcome variable.
  • Parentheses are used to execute the function through the variable.

Concepts Covered:

  • Anonymous functions
  • Function expressions
  • Calling functions through variables

Question 2: Pass Arguments to an Anonymous Function

Problem Statement:
Create an anonymous function that accepts a student’s name and course name. Display both details.

PHP Solution:

<?php
$studentDetails = function($name, $course) {
    echo "Student Name: " . $name . "\n";
    echo "Course Name: " . $course;
};

$studentDetails("Rahul", "PHP");
?>

Sample Output:

Student Name: Rahul
Course Name: PHP

Explanation:

  • The anonymous function accepts two parameters.
  • $name receives the student’s name.
  • $course receives the course name.
  • The function is executed using the $studentDetails variable.

Concepts Covered:

  • Anonymous function parameters
  • Passing arguments
  • Function execution

Question 3: Return a Value from an Anonymous Function

Problem Statement:
Create an anonymous function that accepts two numbers and returns their multiplication result.

PHP Solution:

<?php
$multiply = function($a, $b) {
    return $a * $b;
};

$result = $multiply(12, 5);

echo "Multiplication Result: " . $result;
?>

Sample Output:

Multiplication Result: 60

Explanation:

  • The anonymous function accepts two numbers.
  • The return statement sends their multiplication result back.
  • The returned value is stored in $result.
  • The result is displayed using echo.

Concepts Covered:

  • Returning values
  • Anonymous function parameters
  • Function expressions

Question 4: Use an Anonymous Function with array_map()

Problem Statement:
Create an array of product prices. Use an anonymous function with array_map() to increase every product price by 10%.

PHP Solution:

<?php
$prices = [500, 1000, 1500, 2000];

$updatedPrices = array_map(function($price) {
    return $price + ($price * 10 / 100);
}, $prices);

echo "Updated Prices:\n";

print_r($updatedPrices);
?>

Sample Output:

Updated Prices:
Array
(
    [0] => 550
    [1] => 1100
    [2] => 1650
    [3] => 2200
)

Explanation:

  • $prices contains the original product prices.
  • array_map() applies the anonymous function to every array element.
  • The function increases each price by 10%.
  • The updated values are stored in $updatedPrices.

Concepts Covered:

  • Anonymous functions as callbacks
  • array_map()
  • Array transformation

Question 5: Use a Closure with the use Keyword

Problem Statement:
Create a variable named $bonus with a value of 5,000. Create an anonymous function that accepts an employee’s salary and uses $bonus to calculate the final salary.

PHP Solution:

<?php
$bonus = 5000;

$calculateSalary = function($salary) use ($bonus) {
    return $salary + $bonus;
};

$result = $calculateSalary(30000);

echo "Final Salary: " . $result;
?>

Sample Output:

Final Salary: 35000

Explanation:

  • $bonus is declared outside the anonymous function.
  • The use ($bonus) syntax makes the variable available inside the function.
  • The function adds the bonus to the employee’s salary.
  • An anonymous function that captures variables from its surrounding scope is commonly called a closure.

Concepts Covered:

  • Closures
  • use keyword
  • Variable scope
  • Capturing external variables

Question 6: Modify an External Variable Using a Closure

Problem Statement:
Create a variable named $totalSales with an initial value of zero. Use a closure with reference capture to add multiple sales amounts to the original variable.

PHP Solution:

<?php
$totalSales = 0;

$addSales = function($amount) use (&$totalSales) {
    $totalSales = $totalSales + $amount;
};

$addSales(5000);
$addSales(3000);
$addSales(7000);

echo "Total Sales: " . $totalSales;
?>

Sample Output:

Total Sales: 15000

Explanation:

  • $totalSales is declared outside the closure.
  • use (&$totalSales) captures the variable by reference.
  • The closure modifies the original variable instead of working with a separate copy.
  • Each function call adds another sales amount to the running total.

Concepts Covered:

  • Closure reference capture
  • use keyword
  • Reference variables
  • Running totals

Question 7: Use an Anonymous Function with array_filter()

Problem Statement:
Create an array of student marks. Use an anonymous function with array_filter() to return only students who scored 40 or above.

PHP Solution:

<?php
$marks = [85, 32, 67, 25, 90, 45];

$passedMarks = array_filter($marks, function($mark) {
    return $mark >= 40;
});

echo "Passed Students' Marks:\n";

print_r($passedMarks);
?>

Sample Output:

Passed Students' Marks:
Array
(
    [0] => 85
    [2] => 67
    [4] => 90
    [5] => 45
)

Explanation:

  • array_filter() checks each element using the anonymous function.
  • The function returns true for marks of 40 or above.
  • Only matching values are included in the resulting array.
  • The original array keys are preserved.

Concepts Covered:

  • Anonymous functions
  • array_filter()
  • Callback functions
  • Array filtering

Question 8: Sort Products Using an Anonymous Function

Problem Statement:
Create an array of products containing their names and prices. Use usort() with an anonymous function to arrange the products from lowest to highest price.

PHP Solution:

<?php
$products = [
    ["name" => "Laptop", "price" => 45000],
    ["name" => "Mouse", "price" => 500],
    ["name" => "Keyboard", "price" => 1200],
    ["name" => "Monitor", "price" => 12000]
];

usort($products, function($a, $b) {
    return $a["price"] <=> $b["price"];
});

foreach ($products as $product) {
    echo $product["name"] . " - " . $product["price"] . "\n";
}
?>

Sample Output:

Mouse - 500
Keyboard - 1200
Monitor - 12000
Laptop - 45000

Explanation:

  • $products contains multiple associative arrays.
  • usort() sorts the products using a custom comparison function.
  • The anonymous function compares the two product prices.
  • The spaceship operator (<=>) returns a comparison result.
  • The products are arranged in ascending price order.

Concepts Covered:

  • Anonymous callback functions
  • usort()
  • Multidimensional arrays
  • Custom sorting

Question 9: Create and Return a Closure from a Function

Problem Statement:
Create a function named createMultiplier() that accepts a number and returns a closure. The returned closure should multiply any supplied number by the original number.

PHP Solution:

<?php
function createMultiplier($multiplier) {
    return function($number) use ($multiplier) {
        return $number * $multiplier;
    };
}

$double = createMultiplier(2);
$triple = createMultiplier(3);

echo "Double of 10: " . $double(10) . "\n";
echo "Triple of 10: " . $triple(10);
?>

Sample Output:

Double of 10: 20
Triple of 10: 30

Explanation:

  • createMultiplier() accepts a multiplier value.
  • It returns an anonymous function.
  • The use keyword captures the multiplier.
  • $double stores a closure that multiplies numbers by 2.
  • $triple stores another closure that multiplies numbers by 3.

Concepts Covered:

  • Returning closures
  • use keyword
  • Capturing variables
  • Reusable function logic

Question 10: Build an Employee Bonus Calculator Using Closures

Problem Statement:
Create an employee bonus calculator using a closure. The closure should accept an employee’s name and salary, capture a default bonus percentage of 10%, and return the employee’s salary and bonus details.

PHP Solution:

<?php
$bonusPercentage = 10;

$calculateBonus = function($name, $salary) use ($bonusPercentage) {
    $bonus = $salary * $bonusPercentage / 100;

    return [
        "name" => $name,
        "salary" => $salary,
        "bonus" => $bonus,
        "total_salary" => $salary + $bonus
    ];
};

$employee = $calculateBonus("Amit", 40000);

echo "Employee Name: " . $employee["name"] . "\n";
echo "Basic Salary: " . $employee["salary"] . "\n";
echo "Bonus: " . $employee["bonus"] . "\n";
echo "Total Salary: " . $employee["total_salary"];
?>

Sample Output:

Employee Name: Amit
Basic Salary: 40000
Bonus: 4000
Total Salary: 44000

Explanation:

  • $bonusPercentage stores the bonus percentage outside the closure.
  • use ($bonusPercentage) makes it available inside the closure.
  • The closure calculates the employee’s bonus.
  • It returns employee details in an associative array.
  • The returned values are accessed using their array keys.

Concepts Covered:

  • Closures
  • Capturing external variables
  • Salary calculations
  • Returning associative arrays
  • Reusable business logic

Key Takeaways

  • Anonymous functions are functions without declared names.
  • Anonymous functions can be stored in variables.
  • They can accept parameters and return values.
  • Closures in PHP allow anonymous functions to capture variables from their surrounding scope.
  • The use keyword captures external variables.
  • Variables captured normally are captured by value.
  • Using & captures a variable by reference and allows its original value to be modified.
  • Anonymous functions can be used as callbacks with functions such as array_map(), array_filter(), and usort().
  • A function can return a closure for reusable and dynamic operations.

Frequently Asked Questions (FAQs)

1. What is an anonymous function in PHP?

An anonymous function is a function that does not have a declared name. It can be stored in a variable and executed through that variable.

2. What is a closure in PHP?

A closure is an anonymous function that can capture variables from its surrounding scope using the use keyword.

3. What is the difference between anonymous functions and closures?

An anonymous function is a function without a declared name. When it captures external variables from its surrounding scope, it is commonly called a closure.

4. What is the use of the use keyword in PHP?

The use keyword allows an anonymous function to access variables declared outside that function.

5. What is the difference between use ($variable) and use (&$variable)?

use ($variable) captures the variable by value, while use (&$variable) captures it by reference and allows changes to affect the original variable.

6. Can anonymous functions accept parameters?

Yes. Anonymous functions can accept one or multiple parameters, just like normal PHP functions.

7. Can an anonymous function return a value?

Yes. An anonymous function can use the return statement to send a result back to the calling code.

8. Can anonymous functions be used with array_map()?

Yes. An anonymous function can be passed as a callback to array_map() to perform operations on every array element.

9. Can a PHP function return a closure?

Yes. A function can return an anonymous function. The returned closure can then be stored in a variable and executed later.

10. Where are anonymous functions and closures used in PHP?

They are commonly used for callbacks, array processing, custom sorting, event handling, and reusable operations that need access to external variables.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top