PHP Operators

PHP Operators

  • An operator is a special symbol that performs specific operations on one, two, or three operands and then returns a result. 
  • Operators can be grouped according to the number of values they take.
  • Unary operators take only one value, for example, ++ (the increment operator).
  • Binary operators take two values, for example, arithmetic operators familiars like + (plus) and - (minus), and the majority of PHP operators.

Operator Precedence

  • The precedence of an operator specifies how deeply it binds two expressions together. For example, in the expression 1 + 3 * 2, the answer is 7 and not 8 because the multiplication (*) operator has higher precedence than the addition (+) operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 2) * 2 evaluates to 8.
  • When operators have equal precedence, their associativity decides how the operators are grouped. For example, "-" is left-associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and evaluates to -4. "=" on the other hand, is right-associative, so $a = $b = $c is grouped as $a = ($b = $c).
  • Note: Non-associative Operators of equal precedence cannot be used next to each other, for example, 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal because the == operator has lower precedence than the <= operator.
  • Associativity is only meaningful for binary (and ternary) operators. Unary operators are either prefix or postfix so this notion is not applicable. For example !!$a can only be grouped as !(!$a).
  • The use of parentheses, even when not strictly necessary, can often increase the readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.

  • Operator precedence and associativity only determine how expressions are grouped; they do not specify an order of evaluation. In PHP there are different types of operators
  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Increment/Decrement operators
  5. Logical operators
  6. String operators
  7. Array operators
  8. Conditional assignment operators

Leave a comment
No Cmomments yet