Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 879
PHPFan Avatar asked Feb 19 '15 12:02

PHPFan


2 Answers

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');
like image 104
Vlad Bota Avatar answered Nov 15 '22 03:11

Vlad Bota


With PHP 7 you can use the nicer variable-function syntax everywhere. It works with static/instance functions, and it can take an array of parameters. More info here and related question here

$ret = $callable(...$params);
like image 42
mils Avatar answered Nov 15 '22 02:11

mils