• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Operators

PHP Operators

1 June 2009 / Leave a Comment

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!

Filed Under: PHP Tagged With: arithmetic, assignment, boolean, comparison, increment/decrement, logical, php operator precedence, PHP operators, string

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits