← Back to Chapters

PHP array_walk() & array_walk_recursive()

? PHP array_walk() & array_walk_recursive()

? Quick Overview

The array_walk() and array_walk_recursive() functions allow you to apply a user-defined function to each element of an array. These functions are useful for modifying array elements in place or recursively modifying elements in multidimensional arrays.

? Key Concepts

  • array_walk() applies a function to each element of a single-dimensional array.
  • array_walk_recursive() applies a function to all elements of a multidimensional array.
  • Both functions work by reference and directly modify the original array.

? Syntax & Theory

Both functions accept an array and a callback function. The callback receives each value (by reference) so that changes affect the original array.

? Example 1: Using array_walk()

? View Code Example
// Convert all fruit names to uppercase using array_walk()
<?php
$fruits = array("apple", "banana", "cherry");
array_walk($fruits, function(&$value) {
    $value = strtoupper($value);
});
print_r($fruits);
?>

? Explanation

The callback function receives each array value by reference, allowing strtoupper() to directly modify the original array elements.

? Example 2: Using array_walk_recursive()

? View Code Example
// Recursively convert nested array values to uppercase
<?php
$fruits = array(
    "tropical" => array("mango", "pineapple"),
    "berries" => array("strawberry", "blueberry")
);
array_walk_recursive($fruits, function(&$value) {
    $value = strtoupper($value);
});
print_r($fruits);
?>

? Explanation

The recursive version automatically walks through every level of the array and applies the callback to all nested values.

➕ Example 3: Numeric Modification

? View Code Example
// Increase each number by 5 using array_walk()
<?php
$numbers = array(10, 20, 30);
array_walk($numbers, function(&$value) {
    $value += 5;
});
print_r($numbers);
?>

? Interactive Concept Demo

This visual flow shows how array_walk() processes each element sequentially.

? Concept Flow
// Each element passes through the callback function one by one
Array → [Callback Function] → Modified Original Array
[v1, v2, v3] → f(&$v) → [V1, V2, V3]

? Use Cases

  • Formatting array data before output
  • Sanitizing input values
  • Applying bulk numeric transformations
  • Processing deeply nested configuration arrays

✅ Tips & Best Practices

  • Use array_walk() for single-level arrays.
  • Use array_walk_recursive() for nested arrays.
  • Create a copy of the array if original data must be preserved.

? Try It Yourself

  • Increase each user’s age by 1 using array_walk().
  • Convert all nested color names to lowercase.
  • Apply a 10% discount to a list of prices.
  • Double every number in a numeric array.