php - Laravel collection retrieve variable result from each function

I retrieve a laravel collection from a database on which I want to update certain values based on three calculations. But before I do the calculations I first check if all the relevant collection items is not null. I can check if they are null but for some reason cannot rerieve an error variable that has Controller function scope to tell a user that a variable has not been set.

$error_arr = [];
$calculation = FertilApp::calculation($product, $farm, $agent);
$calculation->each(function ($item, $key) {
    if ($item->ha === null) {
        $error_arr[] = 'Prices has been updated';
        $error_arr[] = 'But no calculation has been done, please update following block:' . $item->block;
        return false;
     }
});

The variable $error_arr returns an empty array even though I know the ha key is null. The alternative is to use a normal foreach() loop. I have tried it and it works, but I really want to know why this is not working.

Can someone please help to give me a clue to why this collection each() method is denying my variable access to values from outside the collection method?

EDIT: If I try to pass my variable as a parameter I get the following error message Cannot use a scalar value as an array.

Laravel version: 5.6.39

Answer

Solution:

Try a global statement:

$calculation->each(function ($item, $key) {
   global $error_arr;

$error_arr is empty in your code, because it doesn't exist in the scope of the callback function of your each method. Unlike other languages ??�?�like JavaScript ??�?�variables outside a function aren't accessible by default inside the function. See PHP's documentation on variable scope for details.

Source