9
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

fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
Janaka Pushpakumara
  • 4,769
  • 5
  • 29
  • 34

3 Answers3

37

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;
});
madsroskar
  • 1,138
  • 13
  • 26
2
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

meewog
  • 1,690
  • 1
  • 22
  • 26
0
public function test()
{
    $x = 10;
    $collection = collect([0, 10, 20]);
    $collection = $collection->map(function ($item, $key) use ($x) {
       return $item + $x;
    });
}
Piotr Adam Milewski
  • 14,150
  • 3
  • 21
  • 42
Avinash kumawat
  • 475
  • 6
  • 18