PHP Operators

Learn how to use PHP operators in your scripts. This article explores common PHP operators and looks at operator precedence.

PHP variables are great for storing values in your script, but they're not much use on their own. To manipulate variable values and get useful results, you need to use operators.

What are PHP operators?

PHP operators let you combine values together to produce new values. For example, to add two numbers together to produce a new value, you use the + (addition) operator. The following PHP code displays the number 5:


echo 2 + 3;

The value or values that an operator works on are known as operands.

In this tutorial you look at common PHP operators, and you also explore the concept of operator precedence.

Common PHP operators

There are many PHP operators, but this article concentrates on the ones you're likely to use most often. These can be broken down into the following operator types:

Arithmetic
Carry out arithmetic operations such as addition and multiplication
Assignment
Assign values to variables
Comparison
Compare 2 values
Increment/decrement
Increase or decrease the value of a variable
Logical
Perform Boolean logic
String
Join strings together

The following sections explore each of these operator types.

Arithmetic operators

PHP features 5 arithmetic operators:

Symbol Name Example Result
+ addition echo 7 + 5 12
- subtraction echo 7 - 5 2
* multiplication echo 7 * 5 35
/ division echo 7 / 5 1.4
% modulus echo 7 % 5 2

The first four operators should be self-explanatory. % (modulus) is simply the remainder of dividing the two operands. In this case, 7 divided by 5 is 1 with a remainder of 2, so the result of the modulus operation is 2.

Assignment operators

The basic assignment operator is = (an equals sign). This is used to assign a value to a variable (as shown in the PHP variables tutorial):


$myVariable = 23;

The value to assign doesn't have to be a literal value — it can be any expression. In the following example, $myVariable takes on the value 12:


$firstNum = 7;
$secondNum = 5;
$myVariable = $firstNum + $secondNum;

As with most PHP operators, the assignment operator doesn't just carry out the operation — it also produces a resulting value, which in this case is the value that was assigned. This allows you to write code such as:


$firstNum = 7;
$secondNum = 5;
$anotherVariable = $myVariable = $firstNum + $secondNum;

In this example, $myVariable is assigned the value 12 (the result of $firstNum + $secondNum). This assignment operation also produces a result of 12, which is then assigned to $anotherVariable. So both $myVariable and $anotherVariable end up storing the value 12.

You can also combine many operators with the assignment operator — these are known as combined assignment operators. For example, say you wanted to add 3 to the value of $myVariable. You could write:


$myVariable = $myVariable + 3;

However, with a combined assignment operator, you can simply write:


$myVariable += 3;

Comparison operators

PHP's comparison operators compare 2 values, producing a Boolean result of true if the comparison succeeded, or false if it failed. You often use comparison operators with statements such as if and while.

PHP supports the following 8 comparison operators:

Symbol Name Usage Result
== equal to a == b true if a equals b, otherwise false
!= not equal to a != b true if a does not equal b, otherwise false
=== identical to a === b true if a equals b and they are of the same type, otherwise false
!== not identical to a !== b true if a does not equal b or they are not of the same type, otherwise false
< less than a < b true if a is less than b, otherwise false
> greater than a > b true if a is greater than b, otherwise false
<= less than or equal to a <= b true if a is less than or equal to b, otherwise false
>= greater than or equal to a >= b true if a is greater than or equal to b, otherwise false

PHP displays the value true as the number 1, and the value false as an empty string. So the following lines of code each display 1 because the comparison operations evaluate to true:


echo ( 7 == 7 );
echo ( 3 < 5 );
echo ( 6 === 6 );

The following lines of code each display nothing at all (an empty string) because the comparison operations evaluate to false:


echo ( 7 != 7 );
echo ( 3 > 5 );
echo ( 6 === "6" );

(The last comparison evaluates to false because 6 (an integer) and "6" (a string) are not of the same type, even though their values are essentially equal.)

Increment/decrement operators

These two operators are very simple — they increase or decrease the value of a variable by 1:

Symbol Name Example Result
++ increment $x++ or ++$x Adds 1 to the variable $x
-- decrement $x-- or --$x Subtracts 1 from the variable $x

The increment and decrement operators are handy when looping through a set of data, or when counting in general.

If you place the operator after the variable name then the expression's value is the value of the variable before it was incremented or decremented. For example, the following code displays the number 4, even though $x's value is increased to 5:


$x = 4;
echo $x++;

On the other hand, if you place the operator before the variable name then the expression evaluates to the value of the variable after it was incremented or decremented. For example, this code displays the number 5:


$x = 4;
echo ++$x;

Logical operators

PHP's logical operators combine values using Boolean logic. Each value to be combined is treated as either true or false — for example, 1, true, a non-empty string, and a successful comparison are all considered true, while 0, false, an empty string, and an unsuccessful comparison are all considered false. The true and/or false values are then combined to produce a final result of either true or false.

PHP supports 6 logical operators:

Symbol Name Example Result
&& and a && b true if a and b are true, otherwise false
and and a and b true if a and b are true, otherwise false
|| or a || b true if a or b are true, otherwise false
or or a or b true if a or b are true, otherwise false
xor xor a xor b true if a or b — but not both — are true, otherwise false
! not !a true if a is false; false if a is true

and and or carry out the same operations as && and ||; however the former have lower precedence than the latter. Usually you'll want to use && and ||, rather than and or or.

Here are some examples of logical expressions that evaluate to true:


( 3 > 1 ) && ( 3 < 5 )
true || false
1 xor ""
!0

Meanwhile, here are some expressions that evaluate to false:


( 1 != 1 ) || (2 != 2 )
true && false
1 xor true
!(!0)

(The last expression takes the value zero and applies the "not" operator to produce a value of true, then applies the "not" operator again to produce a value of false.)

PHP's logical operators are often used with comparison operators to make more complex comparisons.

String operators

The main string operator is the . (dot) operator, which is used to join, or concatenate, two or more strings together. For example, the following code displays "Hello there!":


echo "Hello " . "there!";

As with many other operators, you can combine the . operator with the = operator to produce a combined assignment operator (.=). The following code also displays "Hello there!":


$a = "Hello";
$a .= " ";
$a .= "there!";
echo $a;

Operator precedence in PHP

All PHP operators have a precedence, which determines when the operator is applied in an expression. Consider the following expression:


4 + 5 * 6

You could read this expression in one of two ways:

  • Add 5 to 4, then multiply the result by 6 to produce 54
  • Multiply 5 by 6, then add 4 to produce 34

In fact PHP takes the second approach, because the * (multiplication) operator has a higher precedence than the + (addition) operator. PHP first multiplies 5 by 6 to produce 30, then adds 4 to produce 34.

Here's a list of common PHP operators ordered by precedence (highest precedence first):

Operator(s) Description
++ -- increment/decrement
(int) (float) (string) (array) (object) (bool) casting
! logical "not"
* / % arithmetic
+ - . arithmetic and string
< <= > >= <> comparison
== != === !== comparison
&& logical "and"
|| logical "or"
= += -= *= /= .= %= assignment
and logical "and"
xor logical "xor"
or logical "or"

Operators on the same line in the list have the same precedence.

If you want to change the order that operators are applied, use parentheses. The following expression evaluates to 54, not 34:


( 4 + 5 ) * 6

You've looked at the concept of PHP operators, covered all the common operators, and explored operator precedence. You can now combine values and expressions together to produce more useful PHP scripts. Happy coding!

Learn PHP With Ease!

Written by Matt Doyle — ELATED's resident Web programming expert — Beginning PHP 5.3 is a complete introduction to PHP, covering everything in these tutorials and lots more besides. Find out how to:

  • Set up PHP on your computer
  • Use strings, arrays, functions and objects
  • Create interactive Web forms
  • Handle cookies and sessions
  • Work with files on the server
  • Build database-driven sites with MySQL
  • Send emails from your scripts
  • Create images on the fly with PHP
  • Work with regular expressions
  • Write robust, secure PHP applications

...and lots more!

“What a pleasure it's been spending hours and hours studying PHP with this magical book.” — Lulio, Florida
“The book is not only great for learning, but I find myself using it constantly as a reference as well!” — David A. Stoltz

Buy Beginning PHP 5.3 now from Amazon.comBeginning PHP 5.3 or Amazon.co.ukBeginning PHP 5.3.

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page