OPERATORS
PHP contains three types of operators: unary operators, binary operators, and
one ternary operator.
Binary operatorsare used on two operands:
2 + 3
14 * 3.1415
$i – 1
These examples are also simple examples of expressions.
PHP can only perform binary operations on two operands that have the
same type. However, if the two operands have different types, PHP automati-cally converts one of them to the other’s type, according to the following rules
(unless stated differently, such as in the concatenation operator).
Booleans, nulls, and resources behave like integers, and they convert in
the following manner:
☞Boolean: False = 0, True= 1
☞Null = 0
☞Resource = The resource’s # (id)
2.6.1 Binary Operators
2.6.1.1 Numeric Operators All the binary operators (except for the concate-
nation operator) work only on numeric operands. If one or both of the oper-
ands are strings, Booleans, nulls, or resources, they are automatically
converted to their numeric equivalents before the calculation is performed
(according to the previous table). 2.6.1.2 Concatenation Operator (.) The concatenation operatorconcate-
nates two strings. This operator works only on strings; thus, any non-string
operand is first converted to one.
The following example would print out "The year is 2000":
$year = 2000;
print "The year is " . $year;
The integer $yearis internally converted to the string "2000"before it is
concatenated with the string’s prefix, "The year is".
2.6.2 Assignment Operators
Assignment operatorsenable you to write a value to a variable. The first
operand (the one on the left of the assignment operator or l value) must be a
variable. The value of an assignment is the final value assigned to the vari-
able; for example, the expression $var = 5has the value 5(and assigns 5to
$var).In addition to the regular assignment operator =, several other assign-ment operators are composites of an operator followed by an equal sign. These
composite operators apply the operator taking the variable on the left as the
first operand and the value on the right (the r value) as the second operand,
and assign the result of the operation to the variable on the left.
For example:
$counter += 2; // This is identical to $counter = $counter + 2;
$offset *= $counter;// This is identical to $offset = $offset *
➥$counter;
The following list show the valid composite assignment operators:
+=, -=, *=, /=, %=, ^=, .=, &=, |=, <<=, >>=
2.6.2.1 By-Reference Assignment Operator PHP enables you to create vari-ables as aliases for other variables. You can achieve this by using the by-reference
assignment operator =&. After a variable aliases another variable, changes to
either one of them affects the other.
For example:
$name = "Judy";
$name_alias =& $name;
$name_alias = "Jonathan";
print $name;
The result of this example is
Jonathan
When returning a variable by-reference from a function (covered later in
this book), you also need to use the assign by-reference operator to assign the
returned variable to a variable:
$retval =& func_that_returns_by_reference();
2.6.3 Comparison Operators
Comparison operatorsenable you to determine the relationship between
two operands.
When both operands are strings, the comparison is performed lexico-graphically. The comparison results in a Boolean value.
For the following comparison operators, automatic type conversions are
performed, if necessary.
For the following two operators, automatic type conversions are notper-formed and, therefore, both the types and the values are compared.
2.6.4 Logical Operators
Logical operatorsfirst convert their operands to boolean values and then
perform the respective comparison.
Operator Name Value
== Equal to Checks for equality
between two arguments
performing type conver-sion when necessary:
1 == "1"results in true
1 == 1results in true
!= Not equal to Inverse of ==.
> Greater than Checks if first operand is
greater than second
< Smaller than Checks if first operand is
smaller than second
>= Greater than or equal to Checks if first operand is
greater or equal to second
<= Smaller than or equal to Checks if first operand
is smaller or equal to
second
Operator Name Value
=== Identical to Same as ==but the types
of the operands have to
match.
No automatic type conver-sions are performed:
1 === "1"results in
false.
1 === 1results in true.
!== Not identical to The inverse of ===.2.6.4 Logical Operators
Logical operatorsfirst convert their operands to boolean values and then
perform the respective comparison. 2.6.4.1 Short-Circuit Evaluation When evaluating the logical and/oropera-tors, you can often know the result without having to evaluate both operands.
For example, when PHP evaluates 0 && 1,it can tell the result will be false by
looking only at the left operand, and it won’t continue to evaluate the right
one. This might not seem useful right now, but later on, we’ll see how we can
use it to execute an operation only if a certain condition is met.
2.6.5 Bitwise Operators
Bitwise operatorsperform an operation on the bitwise representation of
their arguments. Unless the arguments are strings, they are converted to
their corresponding integer representation, and the operation is then per-formed. In case both arguments are strings, the operation is performed
between corresponding character offsets of the two strings (each character is
treated as an integer).
2.6.6 Unary Operators
Unary operatorsact on one operand.
2.6.7 Negation Operators
Negation operatorsappear before their operand—for example, !$var (!is the
operator, $varis the operand).
2.6.8 Increment/Decrement Operators
Increment/decrement operatorsare unique in the sense that they operate
only on variables and not on any value. The reason for this is that in addition
to calculating the result value, the value of the variable itself changes as well.
As you can see from the previous table, there’s a difference in the value of
post- and pre-increment. However, in both cases, $varis incremented by 1. The
only difference is in the value to which the increment expression evaluates.
Example 1:
$num1 = 5;
$num2 = $num1++;// post-increment, $num2 is assigned $num1's original
➥value
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the
➥original value of $num1, thus, 5Example 2:
$num1 = 5;
$num2 = ++$num1;// pre-increment, $num2 is assigned $num1's
➥incremented value
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the
➥same as the value of $num1, thus, 6
The same rules apply to pre- and post-decrement.
2.6.8.1 Incrementing Strings Strings (when not numeric) are incremented
in a similar way to Perl. If the last letter is alphanumeric, it is incremented by
1. If it was ‘z’, ‘Z’, or ‘9’, it is incremented to ‘a’, ‘A’, or ‘0’ respectively, and the
next alphanumeric is also incremented in the same way. If there is no next
alphanumeric, one is added to the beginning of the string as ‘a’, ‘A’, and ‘1,’
respectively. If this gives you a headache, just try and play around with it.
You’ll get the hang of it pretty quickly.
Note:Non-numeric strings cannot be decremented.
2.6.9 The Cast Operators
PHP provides a C-like way to force a type conversion of a value by using the
cast operators. The operand appears on the right side of the cast operator,
and its result is the converted type according to the following table.
The casting operators change the type of a value and not the type of a
variable. For example:
$str = "5";
$num = (int) $str;
This results in $numbeing assigned the integer value of $str (5), but $str
remains of type string.2.6.10 The Silence Operator
The operator @silences error messages during the evaluation process of an
expression. It is discussed in more detail in Chapter 7.
2.6.11 The One and Only Ternary Operator
One of the most elegant operators is the ?:(question mark) operator. Its for-mat is
truth_expr ? expr1 : expr2
The operator evaluates truth_exprand checks whether it is true. If it is,
the value of the expression evaluates to the value of expr1(expr2is not evalu-ated). If it is false, the value of the expression evaluates to the value of expr2
(expr1is not evaluated).
For example, the following code snippet checks whether $ais set (using
isset()) and displays a message accordingly:
$a = 99;
$message = isset($a) ? '$a is set' : '$a is not set';
print $message;
This example prints the following:
$a is set
PHP contains three types of operators: unary operators, binary operators, and
one ternary operator.
Binary operatorsare used on two operands:
2 + 3
14 * 3.1415
$i – 1
These examples are also simple examples of expressions.
PHP can only perform binary operations on two operands that have the
same type. However, if the two operands have different types, PHP automati-cally converts one of them to the other’s type, according to the following rules
(unless stated differently, such as in the concatenation operator).
Booleans, nulls, and resources behave like integers, and they convert in
the following manner:
☞Boolean: False = 0, True= 1
☞Null = 0
☞Resource = The resource’s # (id)
2.6.1 Binary Operators
2.6.1.1 Numeric Operators All the binary operators (except for the concate-
nation operator) work only on numeric operands. If one or both of the oper-
ands are strings, Booleans, nulls, or resources, they are automatically
converted to their numeric equivalents before the calculation is performed
(according to the previous table). 2.6.1.2 Concatenation Operator (.) The concatenation operatorconcate-
nates two strings. This operator works only on strings; thus, any non-string
operand is first converted to one.
The following example would print out "The year is 2000":
$year = 2000;
print "The year is " . $year;
The integer $yearis internally converted to the string "2000"before it is
concatenated with the string’s prefix, "The year is".
2.6.2 Assignment Operators
Assignment operatorsenable you to write a value to a variable. The first
operand (the one on the left of the assignment operator or l value) must be a
variable. The value of an assignment is the final value assigned to the vari-
able; for example, the expression $var = 5has the value 5(and assigns 5to
$var).In addition to the regular assignment operator =, several other assign-ment operators are composites of an operator followed by an equal sign. These
composite operators apply the operator taking the variable on the left as the
first operand and the value on the right (the r value) as the second operand,
and assign the result of the operation to the variable on the left.
For example:
$counter += 2; // This is identical to $counter = $counter + 2;
$offset *= $counter;// This is identical to $offset = $offset *
➥$counter;
The following list show the valid composite assignment operators:
+=, -=, *=, /=, %=, ^=, .=, &=, |=, <<=, >>=
2.6.2.1 By-Reference Assignment Operator PHP enables you to create vari-ables as aliases for other variables. You can achieve this by using the by-reference
assignment operator =&. After a variable aliases another variable, changes to
either one of them affects the other.
For example:
$name = "Judy";
$name_alias =& $name;
$name_alias = "Jonathan";
print $name;
The result of this example is
Jonathan
When returning a variable by-reference from a function (covered later in
this book), you also need to use the assign by-reference operator to assign the
returned variable to a variable:
$retval =& func_that_returns_by_reference();
2.6.3 Comparison Operators
Comparison operatorsenable you to determine the relationship between
two operands.
When both operands are strings, the comparison is performed lexico-graphically. The comparison results in a Boolean value.
For the following comparison operators, automatic type conversions are
performed, if necessary.
For the following two operators, automatic type conversions are notper-formed and, therefore, both the types and the values are compared.
2.6.4 Logical Operators
Logical operatorsfirst convert their operands to boolean values and then
perform the respective comparison.
Operator Name Value
== Equal to Checks for equality
between two arguments
performing type conver-sion when necessary:
1 == "1"results in true
1 == 1results in true
!= Not equal to Inverse of ==.
> Greater than Checks if first operand is
greater than second
< Smaller than Checks if first operand is
smaller than second
>= Greater than or equal to Checks if first operand is
greater or equal to second
<= Smaller than or equal to Checks if first operand
is smaller or equal to
second
Operator Name Value
=== Identical to Same as ==but the types
of the operands have to
match.
No automatic type conver-sions are performed:
1 === "1"results in
false.
1 === 1results in true.
!== Not identical to The inverse of ===.2.6.4 Logical Operators
Logical operatorsfirst convert their operands to boolean values and then
perform the respective comparison. 2.6.4.1 Short-Circuit Evaluation When evaluating the logical and/oropera-tors, you can often know the result without having to evaluate both operands.
For example, when PHP evaluates 0 && 1,it can tell the result will be false by
looking only at the left operand, and it won’t continue to evaluate the right
one. This might not seem useful right now, but later on, we’ll see how we can
use it to execute an operation only if a certain condition is met.
2.6.5 Bitwise Operators
Bitwise operatorsperform an operation on the bitwise representation of
their arguments. Unless the arguments are strings, they are converted to
their corresponding integer representation, and the operation is then per-formed. In case both arguments are strings, the operation is performed
between corresponding character offsets of the two strings (each character is
treated as an integer).
2.6.6 Unary Operators
Unary operatorsact on one operand.
2.6.7 Negation Operators
Negation operatorsappear before their operand—for example, !$var (!is the
operator, $varis the operand).
2.6.8 Increment/Decrement Operators
Increment/decrement operatorsare unique in the sense that they operate
only on variables and not on any value. The reason for this is that in addition
to calculating the result value, the value of the variable itself changes as well.
As you can see from the previous table, there’s a difference in the value of
post- and pre-increment. However, in both cases, $varis incremented by 1. The
only difference is in the value to which the increment expression evaluates.
Example 1:
$num1 = 5;
$num2 = $num1++;// post-increment, $num2 is assigned $num1's original
➥value
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the
➥original value of $num1, thus, 5Example 2:
$num1 = 5;
$num2 = ++$num1;// pre-increment, $num2 is assigned $num1's
➥incremented value
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the
➥same as the value of $num1, thus, 6
The same rules apply to pre- and post-decrement.
2.6.8.1 Incrementing Strings Strings (when not numeric) are incremented
in a similar way to Perl. If the last letter is alphanumeric, it is incremented by
1. If it was ‘z’, ‘Z’, or ‘9’, it is incremented to ‘a’, ‘A’, or ‘0’ respectively, and the
next alphanumeric is also incremented in the same way. If there is no next
alphanumeric, one is added to the beginning of the string as ‘a’, ‘A’, and ‘1,’
respectively. If this gives you a headache, just try and play around with it.
You’ll get the hang of it pretty quickly.
Note:Non-numeric strings cannot be decremented.
2.6.9 The Cast Operators
PHP provides a C-like way to force a type conversion of a value by using the
cast operators. The operand appears on the right side of the cast operator,
and its result is the converted type according to the following table.
The casting operators change the type of a value and not the type of a
variable. For example:
$str = "5";
$num = (int) $str;
This results in $numbeing assigned the integer value of $str (5), but $str
remains of type string.2.6.10 The Silence Operator
The operator @silences error messages during the evaluation process of an
expression. It is discussed in more detail in Chapter 7.
2.6.11 The One and Only Ternary Operator
One of the most elegant operators is the ?:(question mark) operator. Its for-mat is
truth_expr ? expr1 : expr2
The operator evaluates truth_exprand checks whether it is true. If it is,
the value of the expression evaluates to the value of expr1(expr2is not evalu-ated). If it is false, the value of the expression evaluates to the value of expr2
(expr1is not evaluated).
For example, the following code snippet checks whether $ais set (using
isset()) and displays a message accordingly:
$a = 99;
$message = isset($a) ? '$a is set' : '$a is not set';
print $message;
This example prints the following:
$a is set