You are here:Home»KB»Programming»PHP»array_walk() - Working with an anonymous function
Tuesday, 12 December 2017 12:34

array_walk() - Working with an anonymous function

Written by

This code is incredibly useful for going through an array and applying changes to the individual values without having to create a specific loop to perfom this action. In this example all apostrophes are escaped.

// Walk through the array and escape all apostophes (anonymous function)
array_walk($merged_config, function(&$value, &$key) {
    $value = str_replace("'", "\\'", $value);
});

this also works, without the &$key

// Walk through the array and escape all apostophes (anonymous function)
array_walk($merged_config, function(&$value) {
    $value = str_replace("'", "\\'", $value);
});

keep the '&' it is important. This creates a reference to the object in memory.

Read 2629 times