Nuances of Grouping in PHP
You can enclose operations that have priority in parentheses - this will not be an error. For example, let's enclose the product of numbers in parentheses:
<?php
$a = (2 * 2) + 3;
echo $a; // outputs 7 (result of 4 + 3)
?>
In this case, the parentheses are redundant (multiplication already has priority), but the code is valid. Sometimes such grouping is used in places where the priority of operations is not obvious. As an example, consider the following code:
<?php
$a = 8 / 2 * 4;
echo $a;
?>
As you already know, division will be performed first, and then multiplication. But at first glance, this may not be too obvious. Here you can use grouping parentheses to explicitly show the priority:
<?php
$a = (8 / 2) * 4;
echo $a;
?>
Without running the code, determine what will be output to the screen:
<?php
$a = (2 * 8) / 4;
echo $a;
?>
Without running the code, determine what will be output to the screen:
<?php
$a = 2 * (8 / 4);
echo $a;
?>