Free preview.You're sampling one lesson — enroll free to unlock all 10 lessons and track your progress.
Enroll free
lesson

Closures and Higher-Order Functions

Closures and Higher-Order Functions

In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in PHP and why it matters in real work.

Why it matters

Functions that take or return functions unlock concise, composable code.

Key ideas

  • Functions as values
  • map / filter / reduce
  • Callbacks
  • Composition

In practice

Here's how it looks in idiomatic PHP:

<?php
$nums = [1, 2, 3, 4, 5, 6];

$doubled = array_map(fn($n) => $n * 2, $nums);
$evens   = array_filter($nums, fn($n) => $n % 2 === 0);
$total   = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);

print_r(array_values($evens));   // re-index: [2, 4, 6]

PHP note: array_map/array_filter/array_reduce take callbacks (arrow fns are ideal); note array_filter preserves original keys, so array_values() re-indexes the result.

Try it yourself

Exercise: In PHP, use map and filter to get the squares of the even numbers.

Recap

You now understand closures and higher-order functions and can apply it in PHP. Mark this lesson complete and continue to the next one.