Logic in PHP: 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 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. The special constants false and null also evaluate to false. These six values are false. Everything else is true.

A variable equal to one of the false values, or a function that returns one of those values, also evaluates to false. Every other expression evaluates to 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 concate­nates two strings is the new combined string. The expression ‘jacob’ . ‘@example.com’ equals the string jacob@exanple.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.

Source: Sklar David (2020), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *