Sling Academy
Home/PHP/High Order Functions in PHP: A Practical Guide (6 Examples)

High Order Functions in PHP: A Practical Guide (6 Examples)

Last updated: January 10, 2024

Overview

High order functions are a cornerstone in modern PHP programming, greatly enhancing the way developers write concise and functional code. This guide will explore what high order functions are and how they can be utilized in PHP to simplify your codebase with practical, real-world examples.

Understanding High Order Functions

A high order function is one that either takes a function as an argument, returns a function, or both. PHP offers numerous built-in high order functions that deal with arrays, such as array_map(), array_filter(), and array_reduce(), as well as usort() for sorting.

Example 1: Using array_map()

$numbers = [1, 2, 3, 4, 5];
$squared = array_map(fn($number) => $number ** 2, $numbers);
print_r($squared);

Output:

Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

Example 2: Using array_filter()

$numbers = [1, 'two', 3, 'four', 5];
$integers = array_filter($numbers, 'is_int');
print_r($integers);

Output:

Array
(
    [0] => 1
    [2] => 3
    [4] => 5
)

Example 3: Using array_reduce()

$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, fn($carry, $item) => $carry + $item, 0);
echo $sum;

Output:

15

Creating Custom High Order Functions

You’re not limited to built-in functions; you can create your own high order functions. Let’s say you want to create a function that applies a custom operation to all elements in an array:

Example 4: Custom High Order Function

function array_apply($array, callable $operation) {
    foreach ($array as $key => $value) {
        $array[$key] = $operation($value);
    }
    return $array;
}

$numbers = [1, 2, 3, 4, 5];
$incremented = array_apply($numbers, fn($n) => $n + 1);
print_r($incremented);

Output:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
    [4] => 6
)

Leveraging Anonymous Functions and Closures

PHP’s support for anonymous functions, also known as closures, makes working with high order functions incredibly straightforward. Closures can capture variables from the parent scope, offering flexibility and power in callbacks.

Example 5: Closure with use Keyword

$multiplier = 3;
$numbers = [1, 2, 3, 4, 5];
$scaled = array_map(fn($n) => $n * $multiplier, $numbers);
print_r($scaled);

Output:

Array
(
    [0] => 3
    [1] => 6
    [2] => 9
    [3] => 12
    [4] => 15
)

Advanced Patterns with High Order Functions

Combining multiple high order functions can lead to powerful data processing patterns. For example, you could combine array_map(), and array_filter() to first transform an array and then filter it.

Example 6: Chaining High the functions together

$numbers = [1, 2, 3, 4, 5];
$oddCubed = array_filter(
    array_map(fn($n) => $n ** 3, $numbers),
    fn($n) => $n % 2 !== 0
);
print_r($oddCubed);

Output:

Array
(
    [0] => 1
    [2] => 27
    [4] => 125
)

Conclusion

High order functions offer a robust framework for operating on collections of data in a functional style in PHP. By understanding and applying them, you can write more readable, expressive, and maintainable code. Embrace these tools to take your PHP coding to the next level.

Next Article: Using printf() and sprintf() in PHP

Previous Article: Using Type Hinting in PHP: A Complete Guide

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array