First of all;
Caution
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code.
Sharing my solution, using:
array_combine
, array_map
and array_keys
to prefix all the keys with an $
Fastest way to add prefix to array keys?
Keep in mind that this expects a formula were all the variables exist in $data
strtr
to replace $N
with $data->N
eval()
to calculate the string: calculate math expression from a string using eval
Code:
<?php
// Original data
$data = (Object) [
'formula' => '($N-$D)*100',
'N' => 100,
'D' => 20
];
// Create an object were 'N => 100' is saved as '$N => 100'
$ovars = get_object_vars($data);
$ovars = array_combine(array_map(function($k){ return '$' . $k; }, array_keys($ovars)), $ovars);
// Replace (oa) $N with $ovars['$N']
$sum = strtr($data->formula, $ovars);
// EVAL
$res = eval('return ' . $sum . ';');
// Show result
echo "SUM: $sum\nRESULT: $res";
Result:
SUM: (100-20)*100
RESULT: 8000