Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_walk_recursive, function using variable outside in PHP [duplicate]

Tags:

php

   $total_materials_cost = 0;
   array_walk_recursive($materials, function($item, $key) {
        if (in_array($key, array('id'))) {

                    (....)

                    $total = $material_price * $material['amount'];

                    $total_materials_cost += $total;
                }
            }
        }
    });
echo $total_materials_cost;

For the above code I get error at line $total_materials_cost += $total; , says the variable is undefined - I believe this is because that I am inside a function? But how can I in any way bypass/ make a workaround for this, so it does add to the variable?

like image 648
Karem Avatar asked Sep 02 '12 18:09

Karem


1 Answers

Use the use keyword:

$total_materials_cost = 0;
array_walk_recursive($materials, function($item, $key) use(&$total_materials_cost) {
  if (in_array($key, array('id'))) {
    // (....)
    $total = $material_price * $material['amount'];
    $total_materials_cost += $total;
  }
});
echo $total_materials_cost;

Pass a reference (&) to change a variable outside the closure.

like image 179
knittl Avatar answered Oct 11 '22 15:10

knittl