Hudzilla.org - the homepage of Paul Hudson
Contents > Simple variables and operators > Operators Wish List | Report Bug | About Me ]

3.12.3     Complete operator list

This is NOT the latest copy of this book; click here for the latest version.

As this book aims to be a complete guide to PHP, it would not be right not to list the entire selection of operators in the language, so here goes:

3.12.3.1 Arithmetic Operators

$a + $b

Addition

Sum of $a and $b

$a - $b

Subtraction

Difference between $a and $b

$a * $b

Multiplication

$a multiplied by $b

$a / $b

Division

$a divided by $b

$a % $b

Modulus

Remainder of $a divided by $b

If you have not used modulus since school, here's a quick refresher. To calculate $a % $b, you first perform $a / $b and then return the remainder. For example, if $a were 10 and $b were 3, $b would go into $a 3 whole times (making nine) with a remainder of 1. Therefore, 10 % 3 is 1.

3.12.3.2 Assignment operators

$a = $b

Equals

Sets $a to equal $b

$a =& $b

Reference

Set $a to reference $b

The difference between a standard assignment and references is explained in detail later - for now, you just need to know that a normal variable holds its own value, whereas a reference takes its value from another variable.

3.12.3.3 Bitwise operators

$a & $b

And

Bits set in $a and $b are set

$a | $b

Or

Bits set in $a or $b are set

$a ^ $b

Xor

Bits set in $a or $b, but not both, are set

~$a

Not

Bits set in $a are not set, and vice versa

$a << $b

Shift left

Shift the bits of $a to the left by $b steps. This is equivalent, but faster, to multiplication. Each step counts as "multiply by two"

$a >> $b

Shift right

Shift the bits of $a to the right by $b steps

Bitwise operators aren't used very often, and even then only by more advanced PHP programmers. They manipulate the binary digits of numbers, which is generally a lot more control than many programmers need.

The number eight, for example, is represented in eight-bit binary as 00001000. In a shift left, <<, all the bits literally get shifted one place to the left, giving 00010000, which is equal to sixteen. Eight shifted left by four gives 10000000, which is equal to 128 - the same number you would have gotten by multiplying eight by two four times in a row. That is, 8 x 2 is 16, 16 x 2 is 32, 32 x 2 is 64, and 64 x 2 is 128.

The & (bitwise and) operator compares all the bits in operand one against all the bits on operand two, then returns a result with all the joint bits set. Here's an example, given 52 & 28, we have the eight-bit binary numbers 00110100 (52) and 00011100 (28). PHP creates a result of 00000000, then proceeds to compare each digit in both numbers - whenever it finds a 1 in both values, it puts a one into the result in the same place. Here is how that looks:

001 1 0 1 00 (52)
000
1 1 1 00 (28)
000
1 0 1 00 (20)

Therefore, 52 & 28 gives 20. As you can imagine, the usefulness of bitwise operators is quite limited, however it is best that you know them and not use them than stumble across them some day in someone else's code and not know what they do.

Perhaps the most common bitwise operator is |, which compares bits in operand one against those in operand two, and returns a result with all the bits set in either of them. For example:

00 11 0 1 00 (52) 11 0 1 000 1 (209) 1111 010 1 (245)

The reason the | (bitwise or) operator is so useful is because it allows you to combine many options together. For example, the flock() function for locking files takes a constant as its second parameter that describes how you want to lock the file. If you pass LOCK_EX you lock the file exclusively, if you pass LOCK_SH you lock the file in shared mode, and if you pass LOCK_NB you enable "non-blocking" mode, which stops PHP from waiting if no lock is available.

However, what you want an exclusive lock and not have PHP wait if no lock is available? This is where the bitwise OR operator comes in: you can pass LOCK_EX | LOCK_NB, and PHP combines the two into one parameter that does both.

3.12.3.4 Comparison operators

All comparison operators return either true or false, and so are suitable for use in conditions.

$a == $b

Equals

True if $a is equal to $b

$a === $b

Identical

True if $a is equal to $b, and of the same type

$a != $b

Not equal

True if $a is not equal to $b

$a <> $b

Not equal

True if $a is not equal to $b

$a !== $b

Not identical

True if $a is not equal to $b or if they are not of the same type

$a < $b

Less than

True if $a is less than $b

$a > $b

Greater than

True if $a is greater than $b

$a <= $b

Less than or equal

True if $a is less than or equal to $b

$a >= $b

Greater than or equal

True if $a is greater than or equal to $b

On the whole, PHP programmers prefer != to <>, despite them doing the same thing. This bias is down to the fact that much of PHP's syntax is based on C, which uses != exclusively.

The === (identical) operator is used very rarely in comparison to == (equality), but it can be useful on occasion. To make sure you are clear, two variables are only identical if they hold the same value and if they are the same type. Here's a code example to make the point clear:

<?php
    
print 12 == 12;
    print
12 === 12;
    print
"12" == 12;
    print
"12" === 12;
?>

When you run that script using the interactive mode of the CLI SAPI, you will find PHP outputs a 1 for the first three lines, and nothing for the last one. As mentioned already, PHP outputs a 1 for "true", which means that the statements 12 equals 12, 12 is identical to 12, and "12" equals 12 are all true. However, nothing is output for the fourth line, which means that PHP considers the statement "12" is identical to 12 to be false, which is expected - although "12" and 12 are the same value, they are not the same type; the former is a string, and the latter is a number.

3.12.3.5 Incrementing and decrementing operators

>++$a

Pre-increment

Increments $a by one, then returns $a

$a++

Post-increment

Returns $a, then increments $a by one

--$a

Pre-decrement

Decrements $a by one, then returns $a

$a--

Post-decrement

Returns $a, then decrements by one

As you can see, the incrementing and decrementing operators can be placed either before or after a variable, and, confusingly enough, the effect is different depending on where the operator is placed! Here's a code example:

<?php
    $foo
= 5;
    
$bar = $foo++;
    print
"Foo is $foo\n";
    print
"Bar is $bar\n";
?>

That will output the following:

Foo is 6
Bar is 5

The reason behind this is because ++, when placed after a variable, is the post-increment operator, which immediately returns the original value of the variable before incrementing it. In line two of our script, the value of $foo (5) is returned and stored in $bar, then $foo is incremented by one. If we had put the ++ before $foo rather than after it, $foo would have been incremented then returned, which would have made both $foo and $bar 6.

3.12.3.6 Logical operators

$a and $b

And

True if both $a and $b are true

$a && $b

And

True if both $a and $b are true

$a or $b

Or

True if either $a or $b is true

$a || $b

Or

True if either $a or $b is true

$a xor $b

Xor

True if either $a or $b is true, but not both

!$a

Not

True if $a is not true

As you can see, there are two operators for logical AND and two for logical OR - this is to facilitate operator precedence in more complicated expressions. Generally speaking && and || are used, however one common exception involves the die() function - more on that soon.

Note that PHP uses conditional statement short-circuiting, which is a fancy way of saying "if you write code that says A or B must be true and PHP finds A to be true, it will not bother evaluating B because the condition is already satisfied". You can use OR very successfully with function calls so that PHP will attempt to run the first function, and, if that function returns false, PHP will run the second function.





<< 3.12.2 Comparison operators   3.12.4 The Ternary Operator >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
deathgod - 30 Aug 2008

I have reported previous errors in the bug fix and have even offered to fix them but the errors are not corrected so i assume he is to busy to fix them himself and he doesn't reply if he wants me to fix them for him. Someone go on and email him about the >++ error and come back in a week or two and see if its fixed.

Should Paul appoint someone to maintain this book if he is too busy. I am sure there would be lots of volunteers, myself included.

A PHP User - 30 Aug 2008

10100011100011000110100010100010000011111001010101010110

A PHP User - 30 Aug 2008

10100011100011000110100010100010000011111001010101010110

A PHP User - 30 Aug 2008

Really sorry, seems every time I refresh, it posts again.

A PHP User - 30 Aug 2008

Ok, I'm a brand newbie to programming, so let me see if I have this right, about incrementing. Please forgive my syntax

I'm pretending to make a flood limit of two posts max in 5 minutes for a page that would generate an email from an online form. I'm guessing I'd use a cookie to track the user, but...

Once the user has submitted an email through the form, he hits the submit button, and something like this happens?

$posts=0
//lots of code for the form and the submit function
Submit;
$posts++;
$posttime=time();
$postagain=time() + 300;

Then the flood limit...

if ($posts <= 2 && $posttime >= $postagain {
Submit;
} else {
echo "Only two emails are allowed to be sent within 5 minutes, please wait and try again.";
}

Hopefully I'm understanding it.

A PHP User - 30 Aug 2008

Ok, I'm a brand newbie to programming, so let me see if I have this right, about incrementing. Please forgive my syntax

I'm pretending to make a flood limit of two posts max in 5 minutes for a page that would generate an email from an online form. I'm guessing I'd use a cookie to track the user, but...

Once the user has submitted an email through the form, he hits the submit button, and something like this happens?

$posts=0
//lots of code for the form and the submit function
Submit;
$posts++;
$posttime=time();
$postagain=time() + 300;

Then the flood limit...

if ($posts <= 2 && $posttime >= $postagain {
Submit;
} else {
echo "Only two emails are allowed to be sent within 5 minutes, please wait and try again.";
}

Hopefully I'm understanding it.

A PHP User - 30 Aug 2008

Ok, I'm a brand newbie to programming, so let me see if I have this right, about incrementing. Please forgive my syntax

I'm pretending to make a flood limit of two posts max in 5 minutes for a page that would generate an email from an online form. I'm guessing I'd use a cookie to track the user, but...

Once the user has submitted an email through the form, he hits the submit button, and something like this happens?

$posts=0
//lots of code for the form and the submit function
Submit;
$posts++;
$posttime=time();
$postagain=time() + 300;

Then the flood limit...

if ($posts <= 2 && $posttime >= $postagain {
Submit;
} else {
echo "Only two emails are allowed to be sent within 5 minutes, please wait and try again.";
}

Hopefully I'm understanding it.

A PHP User - 30 Aug 2008

why?
>" Your input was "$bar", and the output is now "$foo"." ?
em, u could escape those double quotes or add . between them and variables...

anyway what's so confusing?
you can make it $bar = $foo + 1; and you'll have it 'nice'.
$foo will be an old value, $bar will be the new one...
is it really such a big problem to figure it out?
it was an example for post-increment, not for addition...

Frank - 30 Aug 2008

OK, I don't understand the post increment in 3.12.3.5. Granted, the value of Foo has been incremented by the Bar statement, but I'm looking at Foo not Bar.

If I create a program to show someone how addition works, and their input is $foo and the output is $bar=$foo++, would I have to configure the output screen to read,

" Your input was "$bar", and the output is now "$foo"." ?

That could get confusing (for me as the programmer)pretty quick.

A PHP User - 30 Aug 2008

double post.. damn refresh =/

A PHP User - 30 Aug 2008

>++$a .. that's what happens when you get lazy and cut it right out of an existing statement =)

A PHP User - 30 Aug 2008

>++$a .. that's what happens when you get lazy and cut it right out of an existing statement =)

Robert Renaud - 30 Aug 2008

In 3.12.3.5
The answer given is correct because post-increment is used.
Foo is 6
Bar is 5

Jeff Adams - 30 Aug 2008

In 3.12.3.5:
Shouldn't it be
Foo 5
Bar 6

A PHP User - 30 Aug 2008

True, the ">++$VARIABLE" is an error.
The correct expression is "++$VARIABLE".

A PHP User - 30 Aug 2008

Note the '>++'



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is zero plus five?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow