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
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;
});
                        public function test()
{
    $x = 10;
    $collection = collect([0, 10, 20]);
    $collection = $collection->map(function ($item) use ($x) {
        return $item + $x;
    });
}
Please note that you had return = in your code which is wrong
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With