What are some best practices for breaking down and evaluating complex mathematical expressions in PHP?

When evaluating complex mathematical expressions in PHP, it is best to break down the expression into smaller parts and evaluate them individually. This can help in avoiding errors and improving readability of the code. One approach is to use the eval() function in PHP to evaluate the expression step by step.

<?php

$expression = "2 + (3 * 4) - (5 / 2)";
$parts = preg_split('/([-+*\/])/', $expression, -1, PREG_SPLIT_DELIM_CAPTURE);

$result = null;
foreach ($parts as $key => $part) {
    if ($key % 2 == 0) {
        $result = eval("return $part;");
    } else {
        $operator = $part;
        $nextPart = $parts[$key + 1];
        $result = eval("return $result $operator $nextPart;");
    }
}

echo "Result: " . $result;

?>