Expressions in PHP are formulated in much the same way as other languages. An expression is formed from literal values (integers, strings, floats, Booleans, arrays, and objects), operators, and function calls that return values. An expression has a value and a type; for example, the expression
4 + 7 has the value 11 and the type integer, and the expression
"Kelpie" has the value Kelpie and the type string. PHP automatically converts types when combining values in an expression. For example, the expression
4 + 7.0 contains an integer and a float; in this case, PHP considers the integer as a floating-point number, and the result is a float. The type conversions are largely straightforward; however, there are some traps, which are discussed later in this section.
The precedence of operators in an expression is similar to the precedence defined in any other language. Multiplication and division occur before subtraction and addition, and so on. However, reliance on evaluation order leads to unreadable, confusing code. Rather than memorize the rules, we recommend you construct unambiguous expressions with parentheses, because parentheses have the highest precedence in evaluation.
For example, in the following fragment
$variable is assigned a value of 32 because of the precedence of multiplication over addition:
$variable = 2 + 5 * 6; echo $variable; //32
The result is much clearer if parentheses are used:
$variable = 2 + (5 * 6); echo $variable; //32
But the following example displays the different result, because parentheses have the highest precedence in evaluation.
$variable = (2 + 5) * 6; echo $variable; //42