0

Example:

$number = "50";
//I am simulating the creation of this $variable since this is the value that it gives me in a real server
$variable = "0 - 10"; //$variable must go like this with quotes
$result = $number + $variable; //50 + 0 - 10 expect
echo $result;
//i need result 40

As you can see in the example I need to use the string generated by $variable to use it in a mathematical operation.

Club
  • 111
  • 1
  • 8
  • Where does `"0 - 10"` comes from? – ruleboy21 Jun 19 '22 at 01:47
  • Hello `$variable = get_post_meta($objProduct->get_id(), '_product_multiplicador', true) ?: "0";` Obtain: `0 - 10` It is a wordpress meta value I need to apply the operation with the value of the obtained variable. – Club Jun 19 '22 at 01:50
  • $result = $number + (int)$variable; this modify will consider only first digits valid so will be 50-0=50 –  Jun 19 '22 at 05:45

2 Answers2

1

You can use the eval function to get the job done.

Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

<?php

$number = "50";
$variable = "0 - 10";
eval("\$variable = $variable;");
$result = $number + $variable;
echo $result; // 40
ruleboy21
  • 5,510
  • 4
  • 17
  • 34
0

You can try to use the PHP eval() function to solve your issue but The eval() language construct is very dangerous because it allows the execution of arbitrary PHP code. see https://www.php.net/manual/en/function.eval.php

<?php
 $number = "50";
 //I am simulating the creation of this $variable since this is the value that it gives me in a real server
 $variable = eval("'0 - 10';"); //$variable must go like this with quotes
 $result = $number + $variable; //50 + 0 - 10 expect
 echo $result;
?>
Farjan
  • 146
  • 7