PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 3, 2022

[FIXED] How to access to variable in outside the map function in Laravel PHP

 March 03, 2022     laravel-5, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing