Rihanna
Rihanna

Reputation: 41

How to use array_walk_recursive

How can I use array_walk_recursive() instead of this:

function check_value($val){
  if(is_array($val)){
    foreach($val as $key => $value)
      $val[$key] = check_value($value);
    return $val;
  }

  return clean_value($val);
}

?

Upvotes: 4

Views: 18627

Answers (3)

Karolis
Karolis

Reputation: 9562

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');

Upvotes: 8

nyson
nyson

Reputation: 1055

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!

Upvotes: 1

Jeroen
Jeroen

Reputation: 13257

This should work:

function check_value ( $val ) {
    if ( is_array ( $val ) ) array_walk_recursive ( $val, 'check_value' );
    return clean_value ( $val );
}

Upvotes: 0

Related Questions