|< Day Day Up >|
3.1 Understanding true and false
Every expression in a PHP program has a truth value: true or false. Sometimes that truth value is important because you use it in a calculation, but sometimes you ignore it. Understanding how expressions evaluate to true or to false is an important part of understanding PHP.
Most scalar values are true. All integers and floating-point numbers (except for 0 and 0.0) are true. All strings are true except for two: a string containing nothing at all and a string containing only the character 0. These four values are false. The special constant false also evaluates to false. Everything else is true.
Figuring out the truth value of an expression has two steps. First, figure out the actual value of the expression. Then, check whether that value is true or false. Some expressions have common sense values. The value of a mathematical expression is what you'd get by doing the math with paper and pencil. For example, 7 * 6 equals 42. Since 42 is true, the expression 7 * 6 is true. The expression 5 - 6 + 1 equals 0. Since 0 is false, the expression 5 - 6 + 1 is false.
The same is true with string concatenation. The value of an expression that concatenates two strings is the new, combined string. The expression 'jacob' . '@example.com' equals the string email@example.com, which is true.
The value of an assignment operation is the value being assigned. The expression $price = 5 evaluates to 5, since that's what's being assigned to $price. Because assignment produces a result, you can chain assignment operations together to assign the same value to multiple variables:
$price = $quantity = 5;
This expression means "set $price equal to the result of setting $quantity equal to 5." When this expression is evaluated, the integer 5 is assigned to the variable $quantity. The result of that assignment expression is 5, the value being assigned. Then, that result (5) is assigned to the variable $price. Both $price and $quantity are set to 5.
|< Day Day Up >|