search for in the  
<ExpressionsArithmetic Operators>
Last updated: Thu, 19 May 2005

Chapter 15. Operators

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

The precedence of an operator specifies how "tightly" it binds two expressions together. 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. If operator precedence is equal, left to right associativity is used.

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.

Table 15-1. Operator Precedence

AssociativityOperatorsAdditional Information
non-associativenewnew
right[array()
non-associative++ -- increment/decrement
non-associative! ~ - (int) (float) (string) (array) (object) @ types
left* / % arithmetic
left+ - . arithmetic and string
left<< >> bitwise
non-associative< <= > >= comparison
non-associative== != === !== comparison
left& bitwise and references
left^ bitwise
left| bitwise
left&& logical
left|| logical
left? : ternary
right = += -= *= /= .= %= &= |= ^= <<= >>= assignment
leftand logical
leftxor logical
leftor logical
left,many uses

Left associativity means that the expression is evaluated from left to right, right associativity means the opposite.

Example 15-1. Associativity

<?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
?>
Use parentheses to increase readability of the code.

Note: Although ! has a higher precedence than =, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the output from foo() is put into $a.



User Contributed Notes
Operators
edwardsbc at yahoo dot com
04-May-2005 01:26
In response to npeelman at cfl dot rr dot com
29-Dec-2004 06:22:

You have misunderstood the behaviour of the interpreter.

With out the curly braces and the single quoted key identifier, the interpreter "assumes" you meant your CONSTANT to be a string.  This ONLY works within a parsed (double quoted) string.  And it doesn't help you at all if your array is multi-dimensional. I consider this a very bad habbit because it will get you in trouble elsewhere. Try the following:

<?php
define
('item','AnyOldThing');
define('b',12);

$arr['item']['b'] = 'string';
$arr['AnyOldThing'][12]= 'Maybe not what I intended.';

echo
"This is a {$arr['item']['b']}"; // [1] prints "This is a string".
echo "This is a $arr[item][b]"; // [2] broken
echo $arr[item][b]; // [3] broken
?>
npeelman at cfl dot rr dot com
29-Dec-2004 06:22
Update to message by yasuo_ohgaki at hotmail dot com:

  I know this is an old message but when using an Associative array in a string you do not have to use { and  } to resolve ambiguity.

ex:

Associative Array in string:

$arr['item'] = 'string';

echo "This is {$arr['item']}"; //prints "This is string".

...does work but, so does:

echo "This is $arr[item]"; //prints "This is string".

... simply enclose the whole string with double quotes and leave out the single quotes from around the index name. This simplifies the code and makes things easier to read.
Stopping at the dot completely
01-Sep-2004 04:33
The low precedence of the OR operator is useful for error control statements such as this one:
$my_file = @file ('non_existent_file') or die ("Failed opening file: error was '$php_errormsg'");

Notice the good readability of the code.
22-Aug-2004 12:51
I think warhog's note about the differing precedence between && / AND and || / OR is worth repeating.  Since && and || evaluate before the assignment operator (=) while AND and OR evaluate after it, you can get COMPLETELY different results if you don't fully parenthesise.

I cannot imagine when it would ever be important that those two pairs have differing precedence, but they do.  And I just spent two hours discovering that the hard way because I broke my career-long rule:

*Always fully parenthesise!*
11-Jun-2004 10:22
Warhog wrote: "maybe usefull for some tricky coding and helpfull to prevent bugs :D"

I'm sure Warhog was being facetious, but for the new programmers in the audience I'd like to point out that 'tricky coding' and relying on precedence/order of evaluation are both well-known ways to *produce* bugs.

Use parentheses instead.
09-Jun-2004 08:58
of course this should be clear, but i think it has to be mentioned espacially:

AND is not the same like &&

for example:

<?php $a && $b || $c; ?>
is not the same like
<?php $a AND $b || $c; ?>

the first thing is
(a and b) or c

the second
a and (b or c)

'cause || has got a higher priority than and, but less than &&

of course, using always [ && and || ] or [ AND and OR ] would be okay, but than you should at least respect the following:

<?php $a = $b && $c; ?>
<?php $a
= $b AND $c; ?>

the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN - after that - compare the success of this with the value of $c

maybe usefull for some tricky coding and helpfull to prevent bugs :D

greetz, Warhog
yasuo_ohgaki at hotmail dot com
26-Mar-2001 03:34
About "{" and "}".
Sometimes PHP programmers need to use "{" and "}" to resolve ambiguity. Here is some examples.

Variable Variables:

$foo = "test";
$$bar = "this is";

echo "${$bar} $foo"; // prints "this is test"
Note: it is the same as
echo "$test $foo";

Array in string:

$arr[10][10][10] = "string";

echo "This is {$arr[10][10][10]}"; // prints "This is string"

Associative Array in string:

$arr['item'] = 'string';

echo "This is {$arr['item']}"; //prints "This is string".
yasuo_ohgaki at hotmail dot com
26-Mar-2001 02:53
Other Language books' operator precedence section usually include "(" and ")" - with exception of a Perl book that I have. (In PHP "{" and "}" should also be considered also). However, PHP Manual is not listed "(" and ")" in precedence list. It looks like "(" and ")" has higher precedence as it should be.

Note: If you write following code, you would need "()" to get expected value.

$bar = true;
$str = "TEST". ($bar ? 'true' : 'false') ."TEST";

Without "(" and ")" you will get only "true" in $str.
(PHP4.0.4pl1/Apache DSO/Linux, PHP4.0.5RC1/Apache DSO/W2K Server)
It's due to precedence, probably.
yasuo_ohgaki at hotmail dot com
09-Mar-2001 04:58
Pay additional attention that precedence is listed from LOWER to HIGHER.  Compiler language books list precedence opposite order. (At least, language books that I have, C/C++/Java. Perl book is the same order. I prefer precedence listed from higher to lower, not a big deal though)

<ExpressionsArithmetic Operators>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 18:35:34 2005 EDT