Skip to content
PHP Logo

How can PHP developers optimize their code to handle different operator values effectively and efficiently?

PHP developers can optimize their code to handle different operator values effectively and efficiently by using switch statements instead of multiple if-else conditions. Switch statements are more concise and easier to read, making the code more maintainable. Additionally, using switch statements can improve the performance of the code as it allows for direct comparisons between the operator values and their corresponding actions.

php
$operator = '+';
$num1 = 10;
$num2 = 5;

switch ($operator) {
    case '+':
        $result = $num1 + $num2;
        break;
    case '-':
        $result = $num1 - $num2;
        break;
    case '*':
        $result = $num1 * $num2;
        break;
    case '/':
        $result = $num1 / $num2;
        break;
    default:
        $result = "Invalid operator";
}

echo "Result: " . $result;