6
   $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?

Karem
  • 17,615
  • 72
  • 178
  • 278
  • I find it VERY unlikely that you need a recursive approach. It is more likely, if needing any special iterating at all, that you just need nested loops. If the subarrays have consistent depth, using recursion is needless overhead and `array_walk_recursive()` will unnecessarily visiting every leafnode. This old question really would have benefited from sample input. Also, `in_array()` is another needless overhead. – mickmackusa Dec 03 '19 at 10:07

1 Answers1

17

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.

knittl
  • 246,190
  • 53
  • 318
  • 364