$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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With