Search code examples
phpfunctionrecursioncallbackcallable

How to call the callable function in PHP?


I've one array titled $post_data. I want to pass this array to some function as an argument. Along with this array I've to pass another argument the callable 'function name' as second argument in a function call.

I'm not understanding how to achieve this.

Following is the function body which needs to be called:

//Following is the function to be called
function walk_recursive_remove(array $array, callable $callback) {
  foreach ($array as $k => $v) {
    if (is_array($v)) {
      $array[$k] = walk_recursive_remove($v, $callback);
    } else {
      if ($callback($v, $k)) {
        unset($array[$k]);
      }
    }
  }
  return $array;
}

//Following is the callback function to be called

function unset_null_children($value, $key){
  return $value == NULL ? true : false;
}

The function call that I tried is as follows:

//Call to the function walk_recursive_remove
$result = walk_recursive_remove($post_data, unset_null_children);

Can someone please help me in correcting the mistake I'm making in calling the function?

Thanks in advance.


Solution

  • First, the way to call a function like the way you intend to is by using

    call_user_func()
    

    or

    call_user_func_array()
    

    In your case, because you want to send parameters, you want to use the second one, call_user_func_array().

    You can find more about these on http://php.net/manual/en/language.types.callable.php.

    In the meantime, I simplified your example a bit and created a small example.

    function walk_recursive_remove(array $array, callable $callback) {
        foreach($array as $k => $v){
            call_user_func_array($callback,array($k,$v));
        }
    }
    
    //Following is the callback function to be called
    
    function unset_null_children($key, $value){
      echo 'the key : '.$key.' | the value : '.$value ;
    }
    
    //Call to the function walk_recursive_remove
    $post_data = array('this_is_a_key' => 'this_is_a_value');
    $result = walk_recursive_remove($post_data, 'unset_null_children');