Menu
Coddy logo textTech

Operator Precedence

Part of the Fundamentals section of Coddy's PHP journey — lesson 20 of 71.

When an expression contains multiple operators, PHP follows a specific order called operator precedence. Just like in math, multiplication and division are performed before addition and subtraction.

<?php
echo 5 + 3 * 2; // Outputs: 11, not 16
?>

PHP multiplies 3 × 2 first (getting 6), then adds 5. If operators had equal priority, it would calculate left to right: 5 + 3 = 8, then 8 × 2 = 16. But that's not how it works.

Here's the precedence from highest to lowest for the operators you've learned:

PriorityOperators
Highest** (exponentiation)
High* / %
Low+ -

To override the default order, use parentheses. Operations inside parentheses are always evaluated first:

<?php
echo (5 + 3) * 2;  // Outputs: 16
echo 2 ** 3 * 2;   // Outputs: 16 (8 * 2)
echo 2 ** (3 * 2); // Outputs: 64 (2^6)
?>

When in doubt, use parentheses to make your intentions clear. It makes your code easier to read and prevents unexpected results.

challenge icon

Challenge

Easy

Read three numbers from input: a, b, and c.

Calculate and print the result of the following expression, using parentheses to ensure the addition happens before the multiplication:

(a + b) * c ** 2

This means: first add a and b, then multiply that sum by c raised to the power of 2.

Example:

If the inputs are 2, 3, and 4, the output should be 80 because:

  • First, add 2 + 3 = 5
  • Then, calculate 4 ** 2 = 16
  • Finally, multiply 5 * 16 = 80

Cheat sheet

PHP follows operator precedence rules when evaluating expressions with multiple operators:

PriorityOperators
Highest** (exponentiation)
High* / %
Low+ -
<?php
echo 5 + 3 * 2; // Outputs: 11 (multiplication first)
?>

Use parentheses to override the default order. Operations inside parentheses are evaluated first:

<?php
echo (5 + 3) * 2;  // Outputs: 16
echo 2 ** 3 * 2;   // Outputs: 16 (8 * 2)
echo 2 ** (3 * 2); // Outputs: 64 (2^6)
?>

Try it yourself

<?php
// Read input
$a = intval(fgets(STDIN));
$b = intval(fgets(STDIN));
$c = intval(fgets(STDIN));

// TODO: Write your code below to calculate (a + b) * c ** 2

// Output the result
echo $result;
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals