Detailed code explanation of the calculation formula in string format through eval in PHP

黄舟
Release: 2023-03-06 19:00:01
Original
1341 people have browsed it

Sometimes we have a commission formula for each product, and this formula for calculating commission is stored in the table in the format of string . When we use this calculation formula, it does not As we wrote: $a=2+3*5;, the result can be calculated simply, and it is a string, so we must convert the string into a result that we can process

There are At that time, we had a commission formula for each product, and the formula for calculating the commission was stored in the table in string format. When we used this calculation formula, it did not look like what we wrote: $a=2+3 *5; This is a simple way to calculate the result, and it is a string. Therefore, we must convert the string into a result that we can process
And the eval() function in php can Processing php code, so you can use this to solve: calculation formula stored in string format

For example:

$str='2*(3+12)';
$result=eval("return $str;");
echo $result;
Copy after login

will output: 30

It is the value of expression

The return $str; in eval() is the php code

Of course, the value of variable can also be brought in :

$a=3;
$b=12;
$str='2*($a+$b)';
$result=eval("return $str;");
echo $result;
Copy after login

will output: 30

This way, the code to implement the calculator in PHP is implemented, mainly using the eval function of PHP.

Related articles:

A small function that inserts a string at a specified position in the string

php custom intercepts Chinese string- utf8 version

PHP Development Tips (10)-How to intercept Chinese strings without garbled characters

The above is the detailed content of Detailed code explanation of the calculation formula in string format through eval in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template