'Fill the array item with dependencies on other items in PHP
I have an array and want to fill the some items depend on previous item's values:
$order = array(
'items_price' => 200,
'tax_price' => 18,
'total_price' => function () {
return $order.items_price + $order.tax_price;
})
How can I do that?
Solution 1:[1]
Well, that actually is doable. You cannot reference values in the array from within the array itself; but if you declare variable references for the needed array values, you can pass those references to the closure (function) using use :
$order = array(
'items_price' => ($ip = 200),
'tax_price' => ($tp = 18),
'total_price' => function() use ($ip, $tp) {
return $ip + $tp;
}
);
echo $order['total_price']();
That echoes out 218 ..! But the downside is that the passed references / params are static. Try
$order['items_price'] = 100;
echo $order['total_price']();
The result are a disappointing 218 ... Even though items_price actually are changed to 100, the params passed to total_price are the same as when the array were created. They are not magically updated, the array are not a piece of dynamic code, it is a data structure.
It was a very interesting question indeed, but I do not see any practically use. It seems to me you in this case should use classes instead of arrays.
Solution 2:[2]
If you have only 1 element you can use:
$order = array('items_price' => 200, 'tax_price' => 18);
$order['total_price'] = $order['items_price'] + $order['tax_price'];
Or if you have orders array like this you can use array map
$orders = array_map(
function($element)
{
$element['total_price'] = $element['items_price'] + $element['tax_price'];
return $element;
},
$orders
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | davidkonrad |
| Solution 2 | gguney |
