I am programming in php and I have the following variable :
$calculation = '15-12';
Is there a function allowing me to convert the character string into calculation?
I am programming in php and I have the following variable :
$calculation = '15-12';
Is there a function allowing me to convert the character string into calculation?
Yeah, you can use eval
expression for such case, but it's not recommended (mention by @El_Vanja). It would be better to cast the values to their correct types and do the calculation.
eval
scenario$calculation = '15-12';
$result = eval('return '.$calculation.';');
print $result; // output will be 3
$calculation = '15-12';
$values = explode('-', $calculation);
$result = intval($values[0]) - intval($values[1]);
print $result;
The eval()
function could be used here:
$calculation = '15-12';
$result = eval('return '.$calculation.';');
echo $result; //outputs '3'
You can use eval()
https://www.php.net/manual/en/function.eval
Pay attention that this function execute the string like PHP code and if it contains specific mathematical expression, it will fail. In this case you'll need to parse your string and do calculation by yourself or use an external library.
@aspirinemaga's solution for casting is the approach that I would take.
If it isn't always going to be subtraction (and you want to avoid using eval()) then you could always use strpos
to figure out if it is adding/subtracting/multiplying and then pass it the expression to a switch statement to get your calc.