In PHP, what are some considerations for implementing a basic calculator functionality using explode() instead of eval()?

When implementing a basic calculator functionality in PHP, it's generally not recommended to use the eval() function due to security risks. Instead, you can use the explode() function to split the input string into operands and operators, and then perform the calculations accordingly. This approach is safer and more controlled than using eval().

$input = "5 + 3 - 2 * 4 / 2";
$elements = explode(" ", $input);

$result = (float) $elements[0];

for ($i = 1; $i < count($elements); $i += 2) {
    $operator = $elements[$i];
    $operand = (float) $elements[$i + 1];

    switch ($operator) {
        case "+":
            $result += $operand;
            break;
        case "-":
            $result -= $operand;
            break;
        case "*":
            $result *= $operand;
            break;
        case "/":
            $result /= $operand;
            break;
    }
}

echo "Result: " . $result;