Operators:: Operator Precedence
Operators:: Operator Precedence
An operator is something that you feed with one or more values (or expressions, in programming jargon)
which yields another value (so that the construction itself becomes an expression). So you can think of
functions or constructions that return a value (like print) as operators and those that return nothing (like
echo) as any other thing.
There are three types of operators. Firstly there is the unary operator which operates on only one
value, for example ! (the negation operator) or ++ (the increment operator). The second group are
termed binary operators; this group contains most of the operators that PHP supports, and a list follows
below in the section Operator Precedence.
The third group is the ternary operator: ?:. It should be used to select between two expressions
depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary
expressions with parentheses is a very good idea.
Operator Precedence
For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*")
operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force
precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.
The following table lists the precedence of operators with the highest-precedence operators listed at the
top of the table. Operators on the same line have equal precedence, in which case their associativity
decides which order to evaluate them in.
Left associativity means that the expression is evaluated from left to right, right associativity
means the opposite.
<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
Note: Although = has a lower precedence than most other operators, PHP will still allow expressions
similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.
Arithmetic Operators
Remember basic arithmetic from school? These work just like those.
Table 15.2. Arithmetic Operators
The division operator ("/") returns a float value unless the two operands are integers (or strings that
get converted to integers) and the numbers are evenly divisible, in which case an integer value will be
returned.
Operands of modulus are converted to integers (by stripping the decimal part) before
processing.
Note: Remainder $a % $b is negative for negative $a.
Assignment Operators
The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It
really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This
allows you to do some tricky things:
<?php
?>
In addition to the basic assignment operator, there are "combined operators" for all of the binary
arithmetic, array union and string operators that allow you to use a value in an expression and then set its
value to the result of that expression. For example:
<?php
$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";
?>
Note that the assignment copies the original variable to the new one (assignment by
value), so changes to one will not affect the other.
This may also have relevance if you need to copy something like a large array inside a tight loop.
Since PHP 4, assignment by reference has been supported, using the $var = &$othervar; syntax, but
this is not possible in PHP 3. 'Assignment by reference' means that both variables end up pointing
at the same data, and nothing is copied anywhere. To learn more about references, please read
References explained. As of PHP 5, objects are assigned by reference unless explicitly told otherwise
with the new clone keyword.
Bitwise Operators
Bitwise operators allow you to turn specific bits within an integer on or off. If both the left- and right-
hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.
<?php
echo 12 ^ 9; // Outputs '5'
What is a bit? A bit is a representation of 1 or 0. Basically OFF and ON. Why do computers use such
simple math? Well computers process with electric current so if the current is over a certain level the
computer considers that to mean ON or 1 and if it is under that level it is set to OFF or 0.
What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would
mean every bit is set. We will look at why a byte's maximum value is 255 in just a second.
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
1 1 1 1 1 1 1 1 = 255
How do we get 255?
Lets take it right to left and add up all those values together
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
0 0 0 1 0 1 1 0 = 22
2 + 4 + 16 = 22
Lets look at some other examples of decimal to binary, the ones on the end try for yourself.
43 = 00101011
4 = 00000100
230 = ?
65 = ?
31 = ?
Lets use two variables to get started with the "And" operator &.
The & or "And" operator takes two values and returns a decimal version of the binary values the left and
right variable share. So using our tables above we can see that the only bit these two share is in the 8
position so $a & $b = 8.
$a = 9;
$b = 10;
echo $a & $b;
This would output the number 8. Why?? Well lets see using our table example
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 0 0 1 0 0 1 = 9
$b 0 0 0 0 1 0 1 0 = 10
So you can see from the table the only bit they share together is the 8 bit. So 8 gets returned.. not too hard
eh? Lets look at another example of the & operator.
$a = 36;
$b = 103;
echo $a & $b;
This would output the number 36. Why?? Well lets see using our table example again
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 1 0 0 1 0 0 = 36
$b 0 1 1 0 0 1 1 1 = 103
So you can see the only bits these two share together are the bits 32 and 4 which when added together
return 36. This operator is saying "I want to know what bits you both have set in the same column"
This would output the number 11. Why?? Well lets see using our table example
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 0 0 1 0 0 1 = 9
$b 0 0 0 0 1 0 1 0 = 10
If you notice we have 3 bits set, in the 8, 2, and 1 column.. add those up 8+2+1 and you get 11. It is just
saying "I want to know what bits either one of you guys have set".
This would output the number 3. Why?? Well lets see using our table example
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 0 0 1 0 0 1 = 9
$b 0 0 0 0 1 0 1 0 = 10
The XOR operator wants to know "Tell me what bits you both have set but I dont want any bits you share"
Notice we have 3 bits set but both $a and $b share the 8 bit, we dont want that one, we just want the 2 bit
and the 1 bit that they each have set but don't share. Soooo 2+1 = 3
OK, here is one that gets tricky the ~ operator also known as the "NOT" operator.
$a = 9;
$b = 10;
echo $a & ~$b;
This would output the number 1. Why?? Well lets see using our table example
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 0 0 1 0 0 1 = 9
$b 0 0 0 0 1 0 1 0 = 10
The NOT operator wants to know what is set in $a but NOT set in $b because we marked $b with the
~operator in front of it. So looking at our table we can see the only bit set in $a thats not in $b is 1.
$a = 9;
$b = 10;
echo ~$a & $b;
We get the value 2, because we want the bits set in $b but NOT set in $a this time, so since they both share
the 8 bit, 2 bit is the only one $b has that $a does not.
$a = 16;
echo $a << 2;
This would output the number 64. Why?? Well lets see using our table example
1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a - BEFORE! 0 0 0 1 0 0 0 0 = 16
$a - AFTER! 0 1 0 0 0 0 0 0 = 64
How do we get 64? well bit shifting tells PHP to take the variable $a which in our case is 16 and shift if 2
bits which is basically like saying take 16 and multiply it by 2 twice. So 16 X 2 = 32 x 2 = 64
Here is a VERY simple and watered down user persmissions system. This is great if you have many
classes of persmission for users for example...
a user can...
read articles
write articles
edit articles
be an local Administrator
be a global Administrator
So you can setup your permission rules like this in your configuration file
1. <?php
2. $read = 1;
3. $write = 2;
4. $readwrite = 16;
5. $local_admin = 32;
6. $global_admin = 64;
7.
8. $jim = 96;
9. $mike = 16;
10.
11. echo "Is Mike Allowed to edit? he has an access level of 16<BR>";
12. if($mike & 32)
13. {
14. echo 'YES MIKE CAN EDIT';
15. } else {
16. echo 'NO HE CANNOT';
17. }
18.
19. echo "<BR><BR>Is Jim Allowed to edit? he has an access level of
96<BR>";
20. if($jim & 32)
21. {
22. echo 'YES JIM CAN EDIT';
23. } else {
24. echo 'NO HE CANNOT';
25. }
26. ?>
Using the AND operator we can clearly see if Mike has the 32 bit set that is required for this local admin
operation, not only is Jim a local admin but he's also a global admin with the 64 and 32 bit set giving him
a 96 permission level. Imagine if you had 20 different levels of access in your application, being able
to store all those in a single integer is VERY handy instead of having to do something like
Comparison operators, as their name implies, allow you to compare two values. You may also be
interested in viewing the type comparison tables, as they show examples of various type related
comparisons.
If you compare an integer with a string, the string is converted to a number. If you
compare two numerical strings, they are compared as integers. These rules also apply
to the switch statement.
<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("1" == "1e0"); // 1 == 1 -> true
switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>
For various types, comparison is done according to the following table (in order).
<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
if (count($op1) < count($op2)) {
return -1; // $op1 < $op2
} elseif (count($op1) > count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return null; // uncomparable
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>
See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.
Ternary Operator
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
?>
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if
expr1 evaluates to FALSE.
Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to
the result of a statement. This is important to know if you want to return a variable by reference. The
statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a
warning is issued in later PHP versions.
Note: Is is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using
more than one ternary operator within a single statement is non-obvious:
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any
error messages that might be generated by that expression will be ignored.
If the track_errors feature is enabled, any error message generated by the expression will be saved in the
variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use
it.
<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");
?>
Note: The @-operator works only on expressions. A simple rule of thumb is: if you
can take the value of something, you can prepend the @ operator to it. For instance,
you can prepend it to variables, function and include() calls, constants, and so forth.
You cannot prepend it to function or class definitions, or conditional structures such
as if and foreach, and so forth.
See also error_reporting() and the manual section for Error Handling and Logging functions.
Warning
Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will
terminate script execution. Among other things, this means that if you use "@" to suppress errors from a
certain function and either it isn't available or has been mistyped, the script will die right there with no
indication as to why.
Incrementing/Decrementing Operators
<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>
PHP follows Perl's convention when dealing with arithmetic operations on character
variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into
'[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not
decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
<?php
$i = 'W';
for ($n=0; $n<6; $n++) {
echo ++$i . "\n";
}
?>
X
Y
Z
AA
AB
AC
The reason for the two different variations of "and" and "or" operators is that they operate
at different precedences. (See Operator Precedence.)
<?php
bool(true)
bool(false)
bool(false)
bool(true)
String Operators
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation
of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends
the argument on the right side to the argument on the left side. Please read Assignment Operators for more
information.
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
See also the manual sections on the String type and String functions.
Array Operators
The + operator appends elements of remaining keys from the right handed array to the left handed,
whereas duplicated keys are NOT overwritten.
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
Elements of arrays are equal for the comparison if they have the same key and value.
<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");
See also the manual sections on the Array type and Array functions.
Type Operators
<?php
class MyClass
{
}
class NotMyClass
{
}
$a = new MyClass;
bool(true)
bool(false)
<?php
class ParentClass
{
}
class MyClass extends ParentClass
{
}
$a = new MyClass;
bool(true)
bool(true)
Lastly, instanceof can also be used to determine whether a variable is an instantiated object
of a class that implements an interface:
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
bool(true)
bool(true)
Although instanceof is usually used with a literal classname, it can also be used with another
object or a string variable:
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>
bool(true)
bool(true)
bool(false)
There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload()
if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This
can be worked around by using a dynamic class reference, or a string variable containing the class
name:
Example 15.12. Avoiding classname lookups and fatal errors with instanceof in PHP 5.0
<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>
bool(false)
The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since
been deprecated in favor of instanceof.