In the following code the callback function passed to wrap_map can't see the argument in the outer function, why? (see code comment for detail)

public static function wrap_implode($ar, $wrap, $delim){
  echo "wrap is $wrap"; //wrap is ok
  $res = array_map(function($val){
     echo "wrap is $wrap"; //wrap is not set here!
     return $wrap. $val . $wrap;
   }, $ar);

   return implode($delim, $res);
}
link|improve this question

80% accept rate
feedback

1 Answer

up vote 5 down vote accepted

Because it is in another scope. If you want to use $wrap, try:

function($val) use ($wrap){
   //etc
}

Of course, your function here doesn't need a callback:

return $wrap.implode($wrap.$delim.$wrap,$ar).$wrap;
link|improve this answer
Cool for the use keyword (for a function), I learned something :) – FMaz008 Dec 6 '11 at 19:51
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.