• :
  • :

array_walk: how to use with examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

What is array_walk

Description

The array_walk applies a callback function to every member of an array.

Function Signature

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

Arguments

  • array   –   The input array
  • callback –   A function that applies to every member of an array (See notes below)
  • arg – If this argument is supplied, then it is passed as a third parameter to the callback function

Notes

  • The callback takes two arguments: value and the key corresponding to the keys and values of the array.
  • If arg is supplied, then that is passed as a third argument to the callback function.
  • If the callback is supposed to modify the input array values, the value parameter must be passed through reference.
  • The values of the input array could be changed only. Any attempt to change the input array structure by adding, removing or reordering elements will make the function unpredictable.

Return Type

Returns true

Errors/Exceptions

As of PHP 7.1.0, the function throws ArgumentCountError if more than two arguments are required for the callback. In previous versions, the function generated E_WARNING in a similar case.

Introduction

PHP array_walk function sounds similar to array_walk_recursive that we have seen before. The fundamental difference is obvious from their names. The array_walk_recursive, as the name suggests, recursively applies a callback function to a multidimensional array. That’s why array_walk_recursive is the right pick if we have to work with a multidimensional array. However, there were few caveats about the function that we have seen before.

The array_walk function is different because it doesn’t recurse deep into arrays but works with top-level array elements. Thus it is a convenient way to apply a user-defined function to an array using this function. We can use built-in functions too, but that requires programmers to go an extra mile and define wrappers, as we will see in this article.

So, let’s move on to examples to get familiar with this function and learn important caveats of this function.

array_walk

array_walk : Usage Example#1

We have an array of integers, and we want to multiply all of these integers by two. One way is to define a foreach loop and loop through the array. However, the PHP array walk simplifies the code and does it in a one-liner. Thus keeping the code clean and efficient. Let’s see how.

<?php
 
//Integers array
$integers = [-1000000,-100000,-10000,-1000,-100,-10,0,10,100,1000,10000,100000,1000000];
             
 
array_walk($integers,function(&$value,$key) {
    $value *= 2;
});
 
print_r($integers);
 
/*
OUTPUT
Array
(
    [0] => -2000000
    [1] => -200000
    [2] => -20000  
    [3] => -2000  
    [4] => -200    
    [5] => -20    
    [6] => 0      
    [7] => 20      
    [8] => 200    
    [9] => 2000    
    [10] => 20000  
    [11] => 200000
    [12] => 2000000
)
*/
 
?>

Quite convenient. Have you noticed the & before the first argument in the callback array. That indicates to PHP that the value is passed by reference. If we don’t pass this parameter by reference, the change won’t reflect in the integers array.

array_walk : Usage Example#2

Sometimes we may want to pass a built-in PHP function to the PHP array walk. However, that’s usually not possible because a built-in function signature may not match what array_walk expects in the callback. 

To understand this, we take an example of the PHP strtolower function. This function takes a string and makes it lowercase. The function signature is as follows.

strtolower(string $string): string

Now think for a while, can we pass this function directly as a callback to array_walk? Certainly not because callback expects two arguments fundamentally, as we have seen.

So, what’s the way out. The way out is to use wrapper functions. See the example below.

//Wrapper function for strtolower
function wrapper_strtolower(&$value,$key,$arg=null) {
     $value = strtolower($value);
}  

Observe that the wrapper function’s signature matches the expected callback function signature, accepting two arguments value and key while the third arg argument is optional.

Let’s use that as a callback function in the PHP array walk.

$languages = ["PHP","JAVA","JAVASCRIPT","PYTHON","GO","RUBY","PERL"];
 
array_walk($languages,'wrapper_strtolower');
 
print_r($languages);
 
/*
OUTPUT
Array
(
    [0] => php      
    [1] => java      
    [2] => javascript
    [3] => python    
    [4] => go        
    [5] => ruby      
    [6] => perl      
)
*/

Voila! It works just perfectly. The wrapper function is a downside because we have to make a wrapper function for every built-on function. The good news is that we have a solution for that too. Let’s find this out in the next usage example.

array_walk : Usage Example#3

So we are looking for an efficient way to avoid defining wrappers for built-in functions because it becomes impractical to keep on defining wrappers for virtually every function we want to use in the callback. Instead, we define a wrapper for the array_walk function and make it adaptable for almost every function.
The following example is a wrapped array_walk function.

//A wrapper function for array_walk
function wrapper_arraywalk_referential(&$array,$function,$parameters=array()) {
 
    $reference_function = function(&$value, $key, $userdata) {
        $parameters = array_merge(array($value), $userdata[1]);
        $value = call_user_func_array($userdata[0], $parameters);
    };
 
    array_walk_recursive($array, $reference_function, array($function, $parameters));
}

Let’s use the wrapped PHP array walk in a practical scenario.

$html_elem = ["<div>Hello World</div>","<li>ListItem</li>","<b>Bold</b>","<nav>Navigate</nav>"];
 
wrapper_arraywalk_referential($html_elem,'strip_tags');
 
print_r($html_elem);
 
/*
OUTPUT
Array
(
    [0] => Hello World
    [1] => ListItem  
    [2] => Bold      
    [3] => Navigate  
)
*/

Superb. We have just used the array_walk wrapper function with PHP strip_tags function, applying it to all the HTML elements in the array. We don’t have to define a wrapper for the strip_tags function. So, you can use the wrapper function to call any built-in PHP function or user-defined functions.

Conclusion

This article explains the array_walk function in PHP. We’ve seen several important caveats about the function. If the function is supposed to modify the input array elements, the callback must take the first parameter by reference. Moreover, we have seen wrapper function and used a clever approach by defining a wrapper for the PHP array walk instead of defining wrapper functions for every function we intend to call, which is inefficient and redundant. 

That’s it for this article. We hope you’ve enjoyed it. Stay tuned for more interesting and exciting PHP articles.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.