calculate math expression from a string using eval

How can I sort arrays and data in PHP?
String to float PHP

In this solution, we will learn how to calculate math expressions from a string.

Don’t use eval because eval expects complete lines of code, not just fragments.

solution 1.

$ma = "2+10";

if(preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $ma, $matches) !== FALSE){
    $operator = $matches[2];

    switch($operator){
        case '+':
            $p = $matches[1] + $matches[3];
            break;
        case '-':
            $p = $matches[1] - $matches[3];
            break;
        case '*':
            $p = $matches[1] * $matches[3];
            break;
        case '/':
            $p = $matches[1] / $matches[3];
            break;
    }

    echo $p;
}
How can I sort arrays and data in PHP?
String to float PHP
en English
X
Scroll to Top