PHP implements string format calculation formula through eval

墨辰丷
Release: 2023-03-27 20:16:02
Original
1689 people have browsed it

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

Sometimes we have There is a commission formula, and the formula for calculating the commission is stored in the table in string format. When we use this calculation formula, it is not as simple as what we wrote: $a=2 3*5; The result is output, and it is a string. Therefore, we must convert the string into a result that we can process
The eval() function in php can process php code, so this can be used to solve the problem: with a string The calculation formula stored in the format

, for example:

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

will output: 30

is the value of the expression

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

Of course, you can also bring in the value of the variable:

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

Will output: 30

In this way, the code for implementing the calculator in PHP is implemented, mainly using the eval function of PHP.

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHP implementation for mixed Chinese and EnglishStringLength judgment and interception method

php str_getcsv implements the method of parsing string into an array

php custom function to implement statistics in Chinese StringLength method detailed explanation

The above is the detailed content of PHP implements string format calculation formula through eval. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!