PHP comes with a number of operators for working on your data, and they appear in Table A-1. For example, here are the PHP math operators:
You can see them all at work in this example: <HTML> <BODY> <H1>Using the PHP math operators</H1> <?php echo "9 + 4 = ", 9 + 4; echo "9 - 4 = ", 9 - 4; echo "9 * 4 = ", 9 * 4; echo "9 / 4 = ", 9 / 4; echo "9 % 4 = ", 9 % 4; ?> </BODY> </HTML> Operator precedence is also an issueif you evaluate this statement, what would be the result? <?php echo 4 + 2 * 9; ?> Will this be 4 + 2 * 9 = 6 * 9 = 54, or will the * be evaluated first, giving 4 + 2 * 9 = 4 + 18 = 22? In this case, you get 22 because the * operator has precedence over the + operator when you mix them up. Operator precedence, from highest to lowest, is shown in Table A-2.
You can always use parentheses to tell PHP what to do if you're unsure about precedence. If you change this expression to (4 + 2) * 9, then you'll get 6 * 9 = 54: <?php echo "4 + 2 * 9 = ", 4 + 2 * 9; echo "(4 + 2) * 9", (4 + 2) * 9; echo "4 + (2 * 9)", 4 + (2 * 9); ?> Here, you'd get 22, 54, and 22. |