PHP Arrays
Applying a Function to Each Element in an Array
Problem
You want to apply a function or method to each element in an array. This allows you to transform the input data for the entire set all at once.Solution
Use array_walk():$names = array('firstname' => "Baba",
'lastname' => "O'Riley");
array_walk($names, function (&$value, $key) {
$value = htmlentities($value, ENT_QUOTES);
});
foreach ($names as $name) {
print "$name\n";
}
Baba
O'Riley
For nested data, use array_walk_recursive():
$names = array('firstnames' => array("Baba", "Bill"),
'lastnames' => array("O'Riley", "O'Reilly"));
array_walk_recursive($names, function (&$value, $key) {
$value = htmlentities($value, ENT_QUOTES);
});
foreach ($names as $nametypes) {
foreach ($nametypes as $name) {
print "$name\n";
}
}
Baba
Bill
O'Riley
O'Reilly
Discussion
It’s frequently useful to loop through all the elements of an array. One option is to foreach through the data. However, an alternative choice is the array_walk() function.This function takes an array and a callback function, which is the function that processes the elements of the array. The callback function takes two parameters: a value and a key. It can also take an optional third parameter, which is any additional data you wish to expose within the callback.
Here’s an example that ensures all the data in the $names array is properly HTML encoded. The anonymous callback function takes the array values, passes them to htmlentities() to encode the key HTML entities, and assigns the result back to $value:
$names = array('firstname' => "Baba",
'lastname' => "O'Riley");
array_walk($names, function (&$value, $key) {
$value = htmlentities($value, ENT_QUOTES);
});
foreach ($names as $name) {
print "$name\n";
}
Baba
O'Riley
Because array_walk operates in-place instead of returning a modified copy of the array, you must pass in values by reference when you want to modify the elements. In those cases, as in this example, there is an & before the parameter name. However, this is only necessary when you wish to alter the array.
When you have a series of nested arrays, use the array_walk_recursive() function:
$names = array('firstnames' => array("Baba", "Bill"),
'lastnames' => array("O'Riley", "O'Reilly"));
array_walk_recursive($names, function (&$value, $key) {
$value = htmlentities($value, ENT_QUOTES);
});
foreach ($names as $nametypes) {
foreach ($nametypes as $name) {
print "$name\n";
}
}
Baba
Bill
O'Riley
O'Reilly
The array_walk_recursive() function only passes nonarray elements to the callback, so you don’t need to modify a callback when switching from array_walk().
No comments:
Post a Comment