-1

I have a Laravel ->each() function inside a loop.

I want to be able to get at the loop variables from within the each function.

    foreach ($stringsArray as $string) {
        if (!empty($string)) {
            DBModel::all()->each(function (DBModel $model) {
                    global $string;
                    // $string at this point is nothing/undefined

How can I access $string from within the ->each() function?

This is using laravel 4.2.

With the current code $string is undefined (with or without the global directive).

Emile Bergeron
  • 16,148
  • 4
  • 74
  • 121
Jimmery
  • 9,365
  • 25
  • 78
  • 150
  • 1
    Possible duplicate of [PHP: Callback function using variables calculated outside of it](https://stackoverflow.com/questions/4588714/php-callback-function-using-variables-calculated-outside-of-it) – Emile Bergeron Jul 26 '17 at 15:26

1 Answers1

5

You should use the use keyword to use it in the anonymous scope http://php.net/manual/en/functions.anonymous.php

$example = function () use ($message) {
        var_dump($message);
};

$example();
online Thomas
  • 8,511
  • 5
  • 36
  • 77