Issue
public function test()
{
$x = 10;
$collection = collect([0, 10, 20]);
$collection = $collection->map(function ($item, $key){
return $item + $x;
});
}
I want to access the $x variable within the map function: how to do it?
When I try to get the value I got this error message:
ErrorException: Undefined variable: x
Solution
You need to make sure the anonymous function has access to the variable using the use keyword.
You would use it like this:
$collection = $collection->map(function ($item, $key) use ($x) {
return $item + $x;
});
Answered By - madsroskar
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.