Learn how the array_walk function works

Learn how the array walk function works

There are many ways in PHP to manipulate an array, from filtering to merging, but what does the array_walk function do, how does it work, and how can it be applied in your codebase to apply your own supplied function to each section of a provided array? Let us show you in this tutorial how array walk works with anonymous functions, the performance aspect, and more, all with example code that you can copy into your next PHP project.

array_walk

The array walk "array_walk()" provides PHP devs with a flexible and efficient way to iterate over each array element and perform a custom operation. Unlike the majority of functions in PHP, their design is to do a job that's pre-defined by the PHP itself. Array walk is different, as its function in PHP's core lets you call a custom function you've defined, known as the callback, and perform a set of actions against a provided array element. This is great when the associated array functions don't achieve what you're looking for, and in that instance, creating a custom function with an array walk is a great option. As the name suggests, for each element in your array, PHP will walk each item and apply the given callback result to it.

The syntax of array walk is similar to other PHP array functions, taking as the first parameter an array or object, followed by the callable function, and finally an optional mixed argument parameter that can be supplied to the callback. Once the array walk function has run the array against the callback, PHP will return a bool, which is true.

array_walk(array|object &$array, callable $callback, mixed $arg = null): bool

Let's take a simple PHP example of how the array_walk function works. First, we need to create an array of items, in this case, a simple array containing 10, 20, and 30. Next, we need to pass our "$array" to the array_walk function including the name of our callback function, in this case, "timesByTen". Finally, we need to ensure we've created the callback function that the array walk will use. The "timesByTen" function will expect one parameter which is "$number", and this is what will be used to times the number by 10. As part of the function, it will echo the request including putting a new line at the end, using the backslash escape sequence indicator ("\n"). Using an array walk function might seem slightly overkill for what it is doing in this example, but the function is incredibly useful when working with large arrays which require a lot or even complex logic to it.

$array = [0 => 10, 1 => 20, 2 => 30];
array_walk($array, 'timesByTen');

function timesByTen($number) {
 echo $number * 10 . "\n";
}

# Outputs
100
200
300

array_walk vs foreach performance

You might be wondering what the benefit of using array_walk over foreach might be as array_walk is essentially doing what foreach can do, but it comes down to the separation of iteration logic against performance. There's no question that the performance of foreach under some scenarios outperforms array_walk, in some cases by a long stretch. This is particularly important when working with large arrays, where script performance becomes a very high and important factor. Taking our above example, "times by ten", if we run the same code but increase our array size to 500,000 items we can try and measure performance (in terms of execution time) against the same code but swap out array_walk with a foreach loop. Running an array of this size using both methods, we got approximately a 70% quicker result with foreach vs array_walk. That's a loose test run on our development setup and varies depending on different factors, but pretty huge in terms of execution time!

However, array_walk does offer benefits and there are a few reasons why you might consider array_walk over foreach, despite its potential performance impact.

  • Exiting code compatibility - likely there will be situations where you already have an array_walk function in the code base which given convenience might be easier to continue to use compared to rewriting the PHP loop by converting it to use a foreach loop.
  • Callback flexibility - a huge benefit of array_walk is the callback function, whether that's an anonymous function, arrow function, or defined function it can provide more flexibility, whilst still having access to both key and value items
  • Code reusability - by using the callback function, you can reuse similar code more than once compared to
  • Code structure - by separating the iteration logic from the operation, array_walk can help with code readability and maintainability, especially where you've got array_walk in use already, keeping the project consistent

Working with an associative array with array_walk

It is possible with array_walk to also associative arrays, where array keys are strings and not numeric. Switching our array to use days of the week as string, can now amend our callback function to pass both the key and the item, in this case, the day and the number. For the output, we are now using ucfirst to make the first letter of the day of the week string uppercase, then printing is the day, and then the number it corresponds to.

$array = ['monday' => 1, 'tuesday' => 2, 'wednesday' => 3];
array_walk($array, 'timesByTen');

function timesByTen($number, $day) {
 echo ucfirst($day) . ' is day ' . $number . "\n";
}

# Outputs
Monday is day 1
Tuesday is day 2
Wednesday is day 3

Using array_walk and returning a new array in PHP

When using PHP's array_walk, it is also possible to return a new array as opposed to reusing the same array or echoing, for example. That's because, by default, the array walk function will operate on the original array, directly. Within the callback, it is possible to return a new array and then use that array elsewhere by using an anonymous function by reference and using the "use" keyword to import the given variable.

Using an anonymous function in array_walk

Instead of the callback being another function in your code (like our examples above), you can also use an anonymous function, also known as closures. They've given this name because they enclose the access variables from their surrounding scope. They are given the name anonymous function because they are functions without names, meaning they cannot be used by other parts of the PHP code. They can provide arguments and are a way to use functions on the fly. Therefore certain situations mean that closures are highly flexible and powerful. Their syntax typically looks like the PHP example code below where the use keyword provides a way to "use" the result of the closed-scoped code. closures can be used with other PHP functions such as array_map, array_filter, and usort.

function (<parameters>) use (<variables>) { }

By using closures within array_walk it allows us to return the result on array_walk passing this result into a new array. An example of how this works can be seen below in this PHP closure example, where the result of array_walk is inserted into the "$newArray" variable, and even better still, used elsewhere with the PHP code.

$array = [0 => 10, 1 => 20, 2 => 30];
$newArray = [];

array_walk($array, function ($number, $key) use (&$newArray) {
 $newArray[$key] = $number * 10;
});

print_r($newArray);

# Outputs
Array
(
 [0] => 100
 [1] => 200
 [2] => 300
)

Using array_walk arrow function in PHP 7.4 and higher

Since PHP 7.4, arrow functions provide a more concise syntax for anonymous functions. Within a Closure, it's possible to use both the traditional anonymous function or arrow function and support the same features as anonymous functions. The basic syntax of an arrow function is as follows, using the method "fn(0)" followed by "=>" arrow function, then the expression.

fn(argument_list) => expr

Taking our original example, we can remove the callback function and replace it with an arrow-based function, which gives us the same output, however, the code to do so is much smaller. The benefits of using arrow functions with array_walk are the code is smaller, easier to read, and quicker to write! This is the same for array_filter and array_map.

$array = [0 => 10, 1 => 20, 2 => 30];
array_walk($numbers, fn (&$value) => $value *= 10);

print_r($array);

# Outputs
Array
(
 [0] => 100
 [1] => 200
 [2] => 300
)

array_walk vs array_map

A common question when working with arrays is which PHP function is best suited for the job at hand, and that question is no different when deciding if array_walk or array_map is required. Whilst both are useful functions in their own right and do indeed share similarities, they have distinct functionality differences and usages. Array_walk is designed to be used when you're looking to iterate over an array to perform a customer operation on each element, whereas array_map is designed to create a new array by applying the callback function to each element of the inputting array, which in turn returns an array of the result. Keeping this distinction helps for code readability and consistency. So if your task is to modify the original array, use array_walk and if you require a new array, use array_map.

Multidimensional arrays with array_walk

When working with multidimensional arrays in PHP, you can use the array_walk_recursive function that is similar to array_walk but it traverses the array recursively, including through all nested arrays. Like array_walk, array_walk_recursive will apply the callback function to each element it finds.

Conclusion

PHP's array_walk offers a powerful way to loop arrays and apply custom logic to each array element. An alternative to foreach loops is where you are looking to have the loop logic separated from the loop itself. Take the array's possible size and the impact that could have on your application performance, whilst remembering that array_walk_recursive can help achieve similar results when working with multidimensional arrays.

  • If your array is nested with other arrays (multidimensional), use array_walk_resursive
  • If you are using PHP 7.4 or higher, try using arrow functions to keep the code cleaner
  • Using callback functions helps to separate out the looped logic
  • Where you have a large array and application performance is absolutely key, try using a foreach loop instead
  • Use array_map should you wish for a new array instead, that's been through your callback function logic

Senior PHP developer. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Related Dev Guides

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience, and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all