Search code examples
phpanonymous-functionarray-walk

Anonymous function breaking when upgrading PHP


The following code is suddenly breaking when I switched servers/upgrading from PHP 5.3 to 5.4:

function arrayValRecursive($key, array $arr, $string=false){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    if($string==true){
      return count($val) > 1 ? $val : array_pop($val);
    }
    else {
      return $val;
    }
}

I'm receiving a Parse error: syntax error, unexpected T_FUNCTION error, which seems to be due to the anonymous function in the array_walk_recursive line.

How could I write this function differently to avoid this issue, and why is it happening when upgrading PHP?

Thanks


Solution

  • You are currently using php 5.2 from what I can tell.

    Running a phpinfo() with the code <? echo phpinfo(): ?> would detect the version. From my tests using php 5.2 - 5.5 this only occurs in php 5.2 before lambda functions existed.

    Of course you already know this from our comments, this is for future visitors.