0

I have an array like this:

$variables = array("fsueldo", "fgratificacion");
$values  = array($employee->salary, $employee->gratification);

How you can see $employee->salary is a numeric value and same thing with $employee->gratification so I have str_replace like this one:

$calculation = str_replace($variables, $values, $hr_formula->math);

The variable $hr_formula->math has fsueldo+fgratificacion as value

When I replace... it displays 88000+155000 BUT I do not understand why it does not sum or substract or do the calculation, it displays the replaced values but it does not make the math.. so I wonder why does it not sum in this case? I mean it should display 243000 not 88000+155000.

I forgot to say that the variable $hr_formula->math can be any math calculation I mean it can be fsueldo-fgratificacion or fsueldo*fgratificacion.. so I wonder how can It make the math?

Thanks.

Jis
  • 35
  • 1
  • 7
  • 1
    Echoing a string containing `+` doesn't execute the math. – Barmar Oct 04 '21 at 21:31
  • You can use `eval()` to execute code that's created dynamically. You'll need to change it to a variable assignment. – Barmar Oct 04 '21 at 21:32
  • 1
    generally speaking, eval is considered dangerous and is somewhat avoided for that reason. If you want to do math, just write another function that does simple math for you. Like this one https://stackoverflow.com/questions/18880772/calculate-math-expression-from-a-string-using-eval – Dimi Oct 04 '21 at 21:36
  • Using `eval` is bad advise, especially for a user that is still learning the basic string replacement functions. – Rayne Oct 04 '21 at 21:37
  • why you want do this with str_replace? You can use an array for this. Put your data to an associative array. – Maik Lowrey Oct 04 '21 at 21:38

1 Answers1

1

Short answer: You can't get the numeric value with str_replace.

Longer answer: str_replace has the signature str_replace($search, $replace, $subject, &$count = null): string|array. It replaces text from $search with other text values from $replace. $count can be used to count the number of replaced text snippets.

You are using a simple text replacement function that is not calculating math formulas. To calculate arbitrary formulas, you need a formula interpreter. You should not use eval as proposed in the comments. Search for a proper formula interpreter library or - even simpler and in my opinion the best approach - program the math formulas yourself with custom functions.

Rayne
  • 2,620
  • 20
  • 28