How can I use array_walk_recursive()
instead of this:
function check_value($val){
if(is_array($val)){
foreach($val as $key => $value)
I think this should do the same thing. Note that argument of a function is passed as a reference (i.e. &$value
).
array_walk_recursive($array, function(&$value) {
$value = clean_value($value);
});
For older PHP versions:
function check_value(&$value) {
$value = clean_value($value);
}
array_walk_recursive($array, 'check_value');
This should work:
function check_value ( $val ) {
if ( is_array ( $val ) ) array_walk_recursive ( $val, 'check_value' );
return clean_value ( $val );
}
I would rewrite the clean_value function to take a reference argument. For example, these two snippets are functionally identical:
1:
function clean_value($value) {
//manipulate $value
return $value;
}
$value = clean_value($value);
and
2:
function clean_value(&$value) {
//manipulate $value
}
clean_value($value);
For the latter (2), we can use it in array_walk_recursive as follows:
array_walk_recursive($value_tree, 'clean_value');
If we can't edit clean_value, I would solve it as follows:
$clean_by_reference = function(&$val) {
$val = clean_value($val);
};
array_walk_recursive($value_tree, $clean_by_reference);
Hope this helps!