What is the result of
2 + 2 * 2?
If you thought it's
8, then this lesson is for you ;-) In primary school you've learned about operation priority. Priority defines the order of operations in complex expressions. For example, multiplication and division have higher priority than addition or division, while exponentiation has higher priority than anything else. So, 23 * 2 is
But sometimes we want different, non-standard order. Just like in math, we can use brackets to change the order, like so:
(2 + 2) * 2.
Here are few more examples:
<?php print_r(3 ** (4 - 2)); // => 9 print_r(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14
Be sure to balance all brackets in correct order. This is often a problem for both beginners and experienced programmers alike. To make things easier, put both opening and closing brackets, and then type inside. The editor on our website (and most code editors) do that by automaticaly: you type
(, and the editor adds
). This works for some other symbols, like quotation marks, for example. We'll talk about them later.
Sometimes an expression is too complication to perceive visually. Feel free to put brackets even if then won't change the priority, but will make things clearer:
print_r(8 / 2 + 5 - -3 / 2); // => 10.5
print_r(((8 / 2) + 5) - (-3 / 2)); // => 10.5
Remember: we write code for humans, because it'll be read by people, as opposed to machines that will only execute it. The only thing that matters for the machines is the correctness of code. They don't distinguish between "clear" or "confusing".
Look at the expression:
70 * 3 + 4 / 8 + 2.
Place the brackets correctly, so that both additions (
3 + 4 and
8 + 2) are calculated first. Print the result to screen.