0
$data = json_decode(file_get_contents("php://input"));
$Formula = $data->Formula; //getting value ($N-$D)*100.
$N = $data->Numerator; //getting value 100
$D = $data->Denominator; //getting value 20
    

I am getting JSON values like the above way. I want to inject $N,$D values to the variable of $Formula value. I want Output like below : (100-20)*100 = 8000

konda
  • 185
  • 1
  • 12
  • Could you please [edit] your question to add an example of the `$data`? – 0stone0 May 27 '21 at 15:22
  • You will need to use `eval()`. – Barmar May 27 '21 at 15:23
  • However, this is very dangerous to do with user-supplied data, since it will execute any PHP functions. You really should find some other way to accomplish this that doesn't require evaluating user-supplied formulas. – Barmar May 27 '21 at 15:26
  • i tried eval(). eval("\$Formula = \"$Formula\";"); it combines the values. but i need calculated value that is 8000 – konda May 27 '21 at 15:49

1 Answers1

0

First of all;

Caution

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code.


Sharing my solution, using:

  1. 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

  2. strtr to replace $N with $data->N

  3. 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
0stone0
  • 34,288
  • 4
  • 39
  • 64