0
0
PHPprogramming~5 mins

Array walk function in PHP

Choose your learning style9 modes available
Introduction

The array walk function helps you change or use each item in a list one by one.

You want to add a fixed number to every score in a list.
You want to print each name in a list with a greeting.
You want to change all words in a list to uppercase.
You want to check or count items in a list based on a rule.
Syntax
PHP
<?php
function callback_function(&$value, $key, $user_data) {
    // Change or use $value here
}

array_walk(array &$array, callable $callback, mixed $user_data = null): bool;
?>

The callback function receives the value by reference, so you can change it directly.

The callback also gets the key and optional extra data you pass.

Examples
This adds 5 to each number in the list.
PHP
<?php
function add_five(&$value, $key) {
    $value += 5;
}

$numbers = [1, 2, 3];
array_walk($numbers, 'add_five');
print_r($numbers);
This prints a greeting for each name without changing the list.
PHP
<?php
function greet($value, $key) {
    echo "Hello, $value!\n";
}

$names = ['Anna', 'Bob'];
array_walk($names, 'greet');
This changes all words to uppercase.
PHP
<?php
function to_uppercase(&$value, $key) {
    $value = strtoupper($value);
}

$words = ['apple', 'banana'];
array_walk($words, 'to_uppercase');
print_r($words);
This adds ' fruit' to each word using extra data.
PHP
<?php
function add_suffix(&$value, $key, $suffix) {
    $value .= $suffix;
}

$fruits = ['apple', 'banana'];
array_walk($fruits, 'add_suffix', ' fruit');
print_r($fruits);
Sample Program

This program adds an exclamation mark to each word in the list and shows the list before and after.

PHP
<?php
function add_exclamation(&$value, $key) {
    $value .= '!';
}

$words = ['hello', 'world', 'php'];

// Before change
print_r($words);

// Change each word
array_walk($words, 'add_exclamation');

// After change
print_r($words);
?>
OutputSuccess
Important Notes

Time complexity is O(n) because it visits each item once.

Space complexity is O(1) since it changes items in place.

Common mistake: forgetting to pass the value by reference in the callback, so changes don't apply.

Use array_walk when you want to change or use each item without creating a new list. Use array_map if you want a new list instead.

Summary

array_walk lets you run a function on each item in a list.

You can change items directly by passing them by reference.

You can also pass extra data to the function if needed.