Nyxynyx
Nyxynyx

Reputation: 63619

Undefined variable in foreach loop

When I do a foreach() loop, the current array element's value $recipient is not defined on the line ->to($recipient). Why is this?

PHP Code (throws error)

foreach($recipients as $recipient) {
    Mail::send('emails.invite', $data, function($m){
        $m
            ->from('[email protected]', Auth::user()->name)
            ->to($recipient)
            ->subject('Auth::user()->name has invited you!');
    });
}

Error

Notice: Undefined variable: recipient

PHP Code (NO error)

foreach($recipients as $recipient) {
    echo $recipient;
}

Upvotes: 2

Views: 1857

Answers (2)

Cal
Cal

Reputation: 7157

It's because you're inside the scope of the function.

Assuming you're using the PEAR package here, I don't understand why you're passing a function at all: http://pear.php.net/manual/en/package.mail.mail.send.php

If you meant to be doing this, you can use the use keyword to pass the variable into the function scope:

function($m) use($recipient) {

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157967

You missed the use keyword. Change the code to :

foreach($recipients as $recipient) {
    Mail::send('emails.shareListing', $data, function($m) use($recipient) {
        $m
            ->from('[email protected]', Auth::user()->name)
            ->to($recipient)
            ->subject('Auth::user()->name has shared a listing with you!');
    });
}

See this documentation - especially the third example. Quote:

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header.

Upvotes: 3

Related Questions