Q:

Accessing php variables outside of a method in a function

I'm not understanding why this is not working?
I am working in php and specifically laravel.
When I run it I get an undefined variable exception.
I would think I would get the array of bad_rows?
Also on a side question, how could I refactor this to be cleaner? Should I extract the Excel method to its own function?
I basically am trying to import the list, add it to the database and then I will redirect to the main page with the list of rows that were not imported by flashing it.
Thanks!
public function subscriberImportList(Request $request)
{

    \Excel::filter('chunk')->load($request->file('import_list'))->chunk(100, function($rows) use($request)
    {

        $bad_rows = [];

        foreach($rows as $row) 
        {

            if (is_null($row->name) || is_null($row->street_address) || is_null($row->city)){

                array_push($bad_rows, $row->name);

                }

            else {

                //New Subscriber Instance
                $subscriber = new Subscriber;

                //Set the name
                $subscriber->name = $row->name;

                //Set the street address
                $subscriber->street_address = $row->street_address;

                //Set the city,state zip

                preg_match('/([^,]+),\s*(\w{2})\s*(\d{5}(?:-\d{4})?)/', $row->city, $city_state_zip_seperated);

                if (!$city_state_zip_seperated) {

                    array_push($bad_rows, $row->name);                        

                }
                else {

                    $subscriber->city = $city_state_zip_seperated[1];
                    $subscriber->state = $city_state_zip_seperated[2];
                    $subscriber->zipcode = $city_state_zip_seperated[3];

                    //Persist the subscriber to the database
                    $subscriber->save();
                }
            }
        }

        return $bad_rows;

    });

    dd($bad_rows);

}

A:

You have:
public function subscriberImportList(Request $request) {
    \Excel::[..snip..], function($rows) use($request) {
        $bad_rows = [];
        ^^^^^^^^^^------defined here
        blah blah blah
    });
    dd($bad_rows);
        ^^^^^^^^---used here
}

$bad_rows is only ever defined INSIDE that function($rows) closure, which means it's a local variable inside the closure, and exists nowhere else. So when you try dd($bad_rows), you are using an undefined variable.
What you should have is
public function .... {
     $bad_rows = [];
     ^^^^^^^^^^^^^^^^
     \Exce..... function($row) use($request, $bad_rows) {
                                           ^^^^^^^^^^^^
            blah blah blah
     });
     dd($bad_rows);
}

