PHP For Beginners - Lesson 6


1. You can compare two values for equality with the == comparison operator (for example, if ($a == 23) …).
2. To test whether two values are the same and of the same type, you use the === identity operator (for example, if ($b === '23') …).
3. The results of the expressions are a) FALSE, b) TRUE, c) TRUE, and d) FALSE.
4. The result of !(23 === '23') is TRUE, because 23 is not identical to '23' (they have the same numeric value, but one is a number and one is a string), so the inner part evaluates to FALSE, and the ! (not) operator negates this, turning the final value into TRUE.
5. To set the variable $bulb to the value 1 when the variable $daypart has the value 'night', and 0 when it doesn’t, you can use the ternary expression: $bulb = ($daypart == 'night') ? 1 : 0;.
6. PHP will evaluate the expression 5 * 4 + 3 / 2 + 1 using precedence, with * and / having greater precedence than +. The result will be 5 * 4 (which is 20) plus 3 / 2 (which is 1.5) plus 1, making 22.5, the same as (5 * 4) + (3 / 2) + 1.
7. To force PHP to evaluate the expression 1 + 2 / 3 * 4 – 5 from left to right, you need to place parentheses in appropriate places. There are different ways to do this, including (1 + 2) / 3 * (4 – 5), which increases the precedence of the + and – operators to that of / and *, but requires a human to determine where to place the parentheses. Alternatively, you can systematically parenthesize each pair of operands and their operator in turn, like this (with the final pair not requiring any parentheses): (((1 + 2) / 3) * 4) – 5.
8. The math operators have left-to-right associativity because the value on the left is being applied to the value on the right, by the operator.
9. The assignment operators have right-to-left associativity because the value on the right is being assigned to the item on the left.
10. It is a good idea to place the most likely to be TRUE expression on the left of the || operator because it has left-to-right associativity. This means that the left-hand expression is tested first, and if it evaluates to TRUE, the right-hand expression will not be tested (thus saving processor cycles). The right-hand expression will only be tested if the left-hand one evaluates to FALSE.

PHP For Beginners - Lesson 6

No comments:

Post a Comment