PHP Expressions


Statements, expressions, and operators

  • A PHP statement is code that performs a task. Statements are made up of expressions and operators.
  • An expression is code that evaluates to some value (like a number or a string).
1A numeric literal value
"Hello"A string literal
TRUEA constant literal
$user_nameA variable that stores some type of value
$n + 1A numeric value expression that evaluates to a literal
depending on n's value
  • An operator is a code element that acts on an expression in some way (+, -, ++, etc.). The PHP online Manual contains a list of operators. Note the different types (arithmetic, array, assignment, boolean, string, and so on).

Operations have types

  • Note that certain operators are meant to work with certain types of operands--arithmetic operators are used on arithmetic operands. PHP will try to convert data into the correct type but can't always do so:
"7" * "80"         // This evaluates to 560 (implicit casting)
"hello" * "world"  // This evaluates to 0
  • Converting one type of data to another is called casting. In the first example here the strings "7" and "80" are automatically converted to numbers before being multiplied.
  • Explicit cast operators can be used to convert a datum's type:
$test = 1234;
$test_string = (string)$test;  // Converts 1234 into "1234"

Operators have precedence order

  • Operators have a built-in precedence order that determines the order in which they are applied if parentheses are not used.
2 + 3 * 4   // Evaluates to 14 because * has higher precedence
(2 + 3) * 4  // Evaluates to 20 because parenthese override precedence order

See this precedence table for details.

Relational Operators

  • The equals operator is '==' (double equal sign) to be distinguished from the assignment operator ('='). '1' == 1 evaluates to TRUE (printed as 1 in the browser). 5 == 2*2 evaluates to FALSE (0) which is not displayed.
  • The identity operator is '===' (triple equal sign). '1'===1 is FALSE because they are different types.
  • The inequality operator is '!='.
  • The comparison operators are <, >, <=, >=.
  • The logical (boolean) operators are AND (&&), OR (||), XOR, NOT(!) and are defined by the following truth table.