• Language Reference

Bitwise Operators

Bitwise operators allow evaluation and manipulation of specific bits within an integer.

Example Name Result
And Bits that are set in both and are set.
Or (inclusive or) Bits that are set in either or are set.
Xor (exclusive or) Bits that are set in or but not both are set.
Not Bits that are set in are not set, and vice versa.
Shift left Shift the bits of steps to the left (each step means "multiply by two")
Shift right Shift the bits of steps to the right (each step means "divide by two")

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.

Use parentheses to ensure the desired precedence . For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.

If both operands for the & , | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer.

If the operand for the ~ operator is a string, the operation will be performed on the ASCII values of the characters that make up the string and the result will be a string, otherwise the operand and the result will be treated as integers.

Both operands and the result for the << and >> operators are always treated as integers.

PHP's error_reporting ini setting uses bitwise values, providing a real-world demonstration of turning bits off. To show all errors, except for notices, the php.ini file instructions say to use: E_ALL & ~E_NOTICE

This works by starting with E_ALL: 00000000000000000111011111111111 Then taking the value of E_NOTICE... 00000000000000000000000000001000 ... and inverting it via ~ : 11111111111111111111111111110111 Finally, it uses AND (&) to find the bits turned on in both values: 00000000000000000111011111110111

Another way to accomplish that is using XOR ( ^ ) to find bits that are on in only one value or the other: E_ALL ^ E_NOTICE

error_reporting can also be used to demonstrate turning bits on. The way to show just errors and recoverable errors is: E_ERROR | E_RECOVERABLE_ERROR

This process combines E_ERROR 00000000000000000000000000000001 and 00000000000000000001000000000000 using the OR ( | ) operator to get the bits turned on in either value: 00000000000000000001000000000001

Example #1 Bitwise AND, OR and XOR operations on integers

The above example will output:

Example #2 Bitwise XOR operations on strings

Example #3 Bit shifting on integers

Output of the above example on 32 bit machines:

Output of the above example on 64 bit machines:

Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX .

  • gmp_testbit()
  • gmp_clrbit()

Improve This Page

User contributed notes.

To Top

  • Language Reference

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 right (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 $a = ( $b = 4 ) + 5 ; // $a is equal to 9 now, and $b has been set to 4. ?>

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.

An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

Assignment by Reference

Assignment by reference is also supported, using the " $var = &$othervar; " syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #1 Assigning by reference

The new operator returns a reference automatically, as such assigning the result of new by reference is an error.

The above example will output:

More information on references and their potential uses can be found in the References Explained section of the manual.

Arithmetic Assignment Operators

Example Equivalent Operation
$a += $b $a = $a + $b Addition
$a -= $b $a = $a - $b Subtraction
$a *= $b $a = $a * $b Multiplication
$a /= $b $a = $a / $b Division
$a %= $b $a = $a % $b Modulus
$a **= $b $a = $a ** $b Exponentiation

Bitwise Assignment Operators

Example Equivalent Operation
$a &= $b $a = $a & $b Bitwise And
$a |= $b $a = $a | $b Bitwise Or
$a ^= $b $a = $a ^ $b Bitwise Xor
$a <<= $b $a = $a << $b Left Shift
$a >>= $b $a = $a >> $b Right Shift

Other Assignment Operators

Example Equivalent Operation
$a .= $b $a = $a . $b String Concatenation
$a ??= $b $a = $a ?? $b Null Coalesce
  • arithmetic operators
  • bitwise operators
  • null coalescing operator

Improve This Page

User contributed notes 4 notes.

To Top

CodedTag

  • PHP Bitwise Operators

Bitwise operators in PHP enable programmers to perform operations at the binary level, making it possible to manipulate binary digits (bits) directly.

These operators can be employed for tasks such as setting or clearing specific bits, checking the status of individual bits, and performing various bitwise operations like AND, OR, XOR, left shift, and right shift.

Before we dive in, let’s familiarize ourselves with some details about binary representation.

Understanding Binary Representation

Binary representation is the fundamental system computers use to store and process data. In the binary system, digits, or bits, can only take on two values: 0 or 1. These bits are the building blocks of binary numbers, where each position represents a power of 2. For instance, the rightmost bit corresponds to 2^0, the next to 2^1, and so on.

To convert binary to decimal, you add up the decimal values of each bit based on its position. For example, the binary number 101010 translates to

  • 2 5 ×1=3225×1=32
  • 2 4 ×0=024×0=0
  • 2 3 ×1=823×1=8
  • 2 2 ×0=022×0=0
  • 2 1 ×1=221×1=2
  • 2 0 ×0=020×0=0

Adding these values together (32+0+8+0+2+032+0+8+0+2+0), we get the decimal number 42.

To better understand, please refer to the figure below.

System Of Binary Bits

In computing, binary is extensively used for memory storage. Each bit in a binary number can represent the state of a memory cell, either 0 or 1. This binary representation is also the foundation for interpreting digital signals in computers and communication systems. In digital electronics, signals are often categorized as low voltage (0) or high voltage (1).

One practical application of binary representation is in bitwise operations, where individual bits in binary numbers are manipulated. Let’s delve into these operators in the following sections.

Bitwise AND Operator (&)

The bitwise AND operator (&) in PHP is used to perform a bitwise AND operation on each bit of two integers. It compares each bit of the first operand with the corresponding bit of the second operand, and the result is 1 only if both bits are 1. If either or both of the bits are 0, the result is 0.

Let’s take an example using two integers, a= 55 (Binary: 110111) and b = 100 (Binary: 1100100)

Here’s the bitwise AND operation for each bit:

So, $a equals 55 which is “110111”, as calculated from the binary representation shown in the figure below.

Calculate Binary Bits

Similarly, you need to obtain the binary representation of $b for the final calculation, as illustrated in the following figure.

Bitwise AND (&) Operator Calculation

In this example, the binary representation of a is 110111 2 and b is 1100100 2 . The bitwise AND operation compares each pair of corresponding bits: 1 & 1 1&1 results in 1 1, 1 & 1 1&1 results in 1 1, 0 & 0 0&0 results in 0 0, 1 & 0 1&0 results in 0 0, 1 & 1 1&1 results in 1 1, and 1 & 0 1&0 results in 0 0. Therefore, the final result of a & b is 1100100 2 , which is equivalent to decimal 36.

Anyway, in the following section, I will discuss the bitwise OR operator. Let’s move forward.

Bitwise OR Operator (|)

The Bitwise OR operator ( | ) is a fundamental operator used in programming languages to perform bitwise OR operations on the individual bits of two integers. In PHP, the Bitwise OR operator is represented by the pipe symbol ( | ). When the Bitwise OR operator is applied to two integers, it compares the corresponding bits of the binary representations of those integers and sets the result bit to 1 If any of the corresponding bits in the operands is set to 1.

For an example:

In this example, we have two integers, $number_1 with a decimal value of 55 and $number_2 with a decimal value of 100. When we apply the Bitwise OR operator ( | ) to these numbers, the binary representations of each number are considered at the bit level.

Bitwise OR Operator

Another explanation for it.

The binary representation of 55 is 110111 , and the binary representation of 100 is 1100100 . Performing the Bitwise OR operation on each corresponding pair of bits, we get the binary result 1110111 , which is equivalent to the decimal value 119.

So, when we echo $result , the output will be 119 , demonstrating the result of applying the Bitwise OR operator to $number_1 and $number_2 .

Let’s proceed to the next section to understand how to extract binaries using the XOR operator.

Bitwise XOR Operator (^)

The Bitwise XOR operator (^) compares each bit of two numbers and returns 1 where the bits are different and 0 where they are the same. In other words, it performs the exclusive OR operation on individual bits.

Let’s see an example:

Here’s a step-by-step explanation:

Bitwise XOR (^) Operator

  • $number_1 in binary is 00110111 .
  • $number_2 in binary is 1100100 .
  • The Bitwise XOR operation is performed on each corresponding pair of bits. When the bits are identical, the outcome is 0; if they differ, the result is 1.
  • The binary result of the XOR operation is 1111111 .
  • So, the output of echo $number_1 ^ $number_2; is 83 .

For another explanation:

Let’s explore another type of bitwise operator in the following section, specifically the bitwise NOT operator.

Bitwise NOT Operator (~)

The Bitwise NOT operator ( ~ ) is a unary operator that is used to perform bitwise negation on the individual bits of an integer. In PHP, the Bitwise NOT operator is represented by the tilde symbol ( ~ ). When the Bitwise NOT operator is applied to an integer, it flips each bit of the binary representation of that integer, changing 0s to 1s and 1s to 0s.

Let’s consider an example in PHP:

In this example, we have an integer $number with a decimal value of 55. When we apply the Bitwise NOT operator ( ~ ) to this number, the binary representation of the number is considered, and each bit is flipped.

The binary representation of 55 is 110111 . Applying the Bitwise NOT operation to each bit, we get the binary result 111000 , which is equivalent to the decimal value -56 in two’s complement form.

So, when we echo $result , the output will be -56 , demonstrating the result of applying the Bitwise NOT operator to $number .

Let’s move on to discussing the bitwise left shift operator in the following section.

Bitwise Left Shift Operator (<<)

The Bitwise Left Shift operator ( << ) is a binary operator used in programming languages to shift the bits of an integer to the left by a specified number of positions. In PHP, the Bitwise Left Shift operator is represented by the double less-than symbol ( << ). When the Bitwise Left Shift operator is applied, each bit in the binary representation of the operand is shifted to the left by a certain number of positions, and zeros are filled in on the right.

For example:

In this example, we have a variable $number with a decimal value of 10, and a variable $push with a value of 4. When we apply the Bitwise Left Shift operator ( << ) to $number by $push positions, each bit in the binary representation of $number is shifted four positions to the left, and zeros are filled in on the right.

The Bitwise Left Shift Operator

The binary representation of 10 is 1010 . Shifting it to the left by 4 positions, we get the binary result 1010000 , which is equivalent to the decimal value 160.

Next, we’ll delve into the details of the bitwise right shift operator in the upcoming section.

Bitwise Right Shift Operator (>>)

The Bitwise Right Shift operator ( >> ) is a binary operator used in programming languages to shift the bits of an integer to the right by a specified number of positions. In PHP, the Bitwise Right Shift operator is represented by the double greater-than symbol ( >> ). When the Bitwise Right Shift operator is applied, each bit in the binary representation of the operand is shifted to the right by a certain number of positions, and zeros are filled in on the left.

In this example, we have a variable $number with a decimal value of 10, and a variable $pull with a value of 2. When we apply the Bitwise Right Shift operator ( >> ) to $number by $pull positions, each bit in the binary representation of $number is shifted two positions to the right, and zeros are filled in on the left.

PHP Bitwise Right Shift Operator

The binary representation of 10 is 1010. Consequently, shifting it to the right by 2 positions yields the binary result 10, which is equivalent to the decimal value 2.

At this point, we have acquired an understanding of the bitwise operator system, but we may be unsure about its practical applications in PHP and the reasons for employing it. In the section below, we will delve into the usage of a common example to illustrate the practical applications of bitwise operators.

Using Bitwise Operators for Flags and Permissions

PHP Bitwise operators are often used in programming to work with flags and permissions efficiently. Flags and permissions are commonly represented using individual bits in an integer, allowing multiple options or settings to be stored compactly within a single variable. This is particularly useful when working with limited resources or when optimizing storage.

Let’s discuss how PHP bitwise operators can be used for flags and permissions with a simple example:

In this example, we employ three constants (READ, WRITE, and EXECUTE) to represent different permissions. Each constant has a unique binary value with a single bit set to 1. Subsequently, we utilize a variable $userPermissions to store the combined permissions.

When it comes to granting permissions, we employ the bitwise OR operator (|) for the process. For instance, $userPermissions = $userPermissions | READ | WRITE; effectively grants both read and write permissions.

Moving on to the checking of permissions, the bitwise AND operator (&) is employed to determine if a specific permission is granted. If the result is non-zero, the permission is indeed granted. For instance, $hasReadPermission = $userPermissions & READ; checks if the read permission is granted.

Let’s summarize it.

Wrapping Up

bitwise operators in PHP provide a powerful means for manipulating binary data directly, enabling programmers to perform operations at the binary level. These operators offer functionalities such as setting or clearing specific bits, checking bit statuses, and executing various bitwise operations like AND, OR, XOR, left shift, and right shift.

Before delving into PHP bitwise operators, understanding binary representation is crucial. The binary system, based on bits that can only be 0 or 1, forms the foundation of computer data storage and processing. Binary representation plays a vital role in tasks like memory storage, digital signal interpretation, and bitwise operations.

The bitwise AND operator (&) compares corresponding bits of two integers, resulting in 1 only if both bits are 1. Meanwhile, the bitwise OR operator (|) sets the result bit to 1 if at least one of the corresponding bits is 1.

Additionally, the bitwise XOR operator (^) returns 1 where bits are different and 0 where they are the same. Moving on to the bitwise NOT operator (~), it performs bitwise negation, flipping each bit of an integer. Finally, the bitwise left shift operator (<<) shifts bits to the left, and the right shift operator (>>) shifts bits to the right.

These operators find applications in various programming scenarios, providing efficient tools for tasks involving binary manipulation. As we continue exploring the intricacies of programming, the understanding and utilization of PHP bitwise operators remain valuable skills.

Thank you for reading. For more tutorials in PHP , please visit this page .

For further reference and detailed information on PHP functions and syntax, you can explore the official PHP manual available at PHP Manual .

Did you find this article helpful?

 width=

Sorry about that. How can we improve it ?

  • Facebook -->
  • Twitter -->
  • Linked In -->
  • Install PHP
  • Hello World
  • PHP Constant
  • PHP Comments

PHP Functions

  • Parameters and Arguments
  • Anonymous Functions
  • Variable Function
  • Arrow Functions
  • Variadic Functions
  • Named Arguments
  • Callable Vs Callback
  • Variable Scope

Control Structures

  • If-else Block
  • Break Statement

PHP Operators

  • Operator Precedence
  • PHP Arithmetic Operators
  • Assignment Operators
  • PHP Comparison Operators
  • PHP Increment and Decrement Operator
  • PHP Logical Operators
  • PHP String Operators
  • Array Operators
  • Conditional Operators
  • Ternary Operator
  • PHP Enumerable
  • PHP NOT Operator
  • PHP OR Operator
  • PHP Spaceship Operator
  • AND Operator
  • Exclusive OR
  • Spread Operator
  • Null Coalescing Operator

Data Format and Types

  • PHP Data Types
  • PHP Type Juggling
  • PHP Type Casting
  • PHP strict_types
  • Type Hinting
  • PHP Boolean Type
  • PHP Iterable
  • PHP Resource
  • Associative Arrays
  • Multidimensional Array

String and Patterns

  • Remove the Last Char

Understanding Bitwise Operators with PHP

bitwise assignment operators php

In this tutorial, you will learn about all 6 bitwise operators in PHP programming with examples.

In the arithmetic-logic unit (within the CPU), mathematical operations like addition, subtraction, multiplication, and division are done at the bit level. Bitwise operators are used to performing bit-level operations in PHP programming.

​ Introduction

Cover of article - Understanding Bitwise Operators with PHP

Bit operations are rare in the PHP world, however, in books, articles, or other sources, you might find something like:

You may get confused. What is >> ? So, let’s look at the documentation .

$a >> $b Shift the bits of $a $b steps to the right (each step means “divide by two”)

​ WTF?! Why do you need it at all?

Many people know that binary (or base-2 ) a numeric system that only uses two digits — 0 and 1 . Computers operate in binary, meaning they store data and perform calculations using only zeros and ones. So, for example, a computer will represent the number 6 as 00000110 .

Bit Rotation : A rotation (or circular shift) is an arithmetic operation.

  • In the left rotation, the bits that fall off at the left end are put back at the right end.
  • In the right rotation, the bits that fall off at the right end are put back at the left end.

​ Let’s back to our operator >> .

We can see that the bits that fall off at the right end are put back at the left end. So the current binary value 00000011 in decimal is 3 . We just shifted one bit, and as a result, we divided the value by 2 .

If we were to shift 2 bits, we would divide by 4 . If we were to shift 3 bits, we would divide by 8 .

​ Wow, that’s the power of two!

Get back to the example >> 20 . It means that we are dividing the value by 2 to the power of 2 0. It is easy to remember that 2 ^ 10 = 1024 . So

Since memory_get_usage() returns a value in bits, we just converted it to megabytes. It turns into a very handy function:

If right rotation means division, then left rotation, on the contrary, means multiplication.

​ Are there other operators besides right/left rotation?

There are 4 more operations - AND & , OR | , XOR ^ , NOT ~ . Let’s see it in action below.

​ What’s the best way to use bitwise operations?

The most convenient to use bitwise operations, not in multiplication and division, but is using a bitwise mask , for example, to differentiate access rights or other similar things.

We can turn four values into a four-bit value, in which 1 means the user has the given right, and 0 does not.

In the first four lines , we defined the constants by shifting bits to the left. After that, we used the OR | operator on the last line. The bitwise OR operator (|) returns a 1 in each bit position for which the corresponding bits of either or both operands are 1s . Example:

Therefore, we can set any permissions for the user:

Access Rights using Binary Masks.png

In the example above, there are 3 new operators.

  • A bitwise XOR operator (^) (performs the logical exclusive OR). It returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1s .
  • The bitwise AND operator (&) returns a 1 in each bit position for which the corresponding bits of both operands are 1s .
  • The bitwise NOT operator (~) inverts the bits of its operand.

​ What happens if we use AND + NOT operators?

In the example below, use the two operators together. The bitwise NOT operator (~) will be executed first, followed by the bitwise AND operator (&) .

​ Is there any difference between the XOR and AND + NOT operators?

The difference between these options is that in the first case, the bit switches. If it was 1 , then it will become 0 , and vice versa. The second option makes the bit equal to 0 , regardless of its current value.

If we want to remove any access right, do the following:

​ A few more examples

To check the bits (in our case, the access rights), we can use the following conditions.

​ One more example

Although error codes in PHP are specially designed for bitwise operations, developers usually use comparison operators. But now you know a different approach 😉

​ Conclution

Thanks for reading this article! I hope you now understand bitwise operators and can utilize them in your PHP code (or in many other languages!). if you have any questions or comments, please reach me out on Twitter . I appreciate any feedback!

Bitwise Operators in PHP : Tutorial

  • PHP - Introduction
  • PHP - Syntax
  • PHP - Comments
  • PHP - Variables
  • PHP - Constants
  • PHP - Data Types
  • PHP - Operators
  • PHP - Echo and Print Statements
  • PHP - Strings
  • PHP - If Else
  • PHP - Switch
  • PHP - While Loop
  • PHP - For Loop
  • PHP - Foreach Loop
  • PHP - goto Statement
  • PHP - Continue Statement
  • PHP - Break Statement
  • PHP - Arrays
  • PHP - Associative Arrays
  • PHP - Sorting Arrays
  • PHP - Functions
  • PHP - Scope of Variables
  • PHP - GET & POST
  • PHP - Predefined Variables
  • PHP - Date & time
  • PHP - Cookies
  • PHP - Classes/Objects
  • PHP - Constructors
  • PHP - Destructors
  • PHP - Encapsulation
  • PHP - Inheritance
  • PHP - Exceptions
  • PHP - Error Handling
  • PHP - Sending Emails
  • PHP & MySQL
  • PHP - Built-In Functions
  • PHP - Data Structures
  • PHP - Examples
  • PHP - Interview Questions

AlphaCodingSkills

Facebook Page

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

PHP - Bitwise XOR and assignment operator

The Bitwise XOR and assignment operator (^=) assigns the first operand a value equal to the result of Bitwise XOR operation of two operands.

(x ^= y) is equivalent to (x = x ^ y)

The Bitwise XOR operator (^) is a binary operator which takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. It returns 1 if only one of the bits is 1, else returns 0.

Bit_1Bit_2Bit_1 ^ Bit_2
000
101
011
110

The example below describes how bitwise XOR operator works:

The code of using Bitwise XOR and assignment operator (^=) is given below:

The output of the above code will be:

Example: Swap two numbers without using temporary variable

The bitwise XOR and assignment operator can be used to swap the value of two variables. Consider the example below.

The above code will give the following output:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

Bitwise operators allow evaluation and manipulation of specific bits within an integer.

Example Name Result
And Bits that are set in both and are set.
Or (inclusive or) Bits that are set in either or are set.
Xor (exclusive or) Bits that are set in or but not both are set.
Not Bits that are set in are not set, and vice versa.
Shift left Shift the bits of steps to the left (each step means "multiply by two")
Shift right Shift the bits of steps to the right (each step means "divide by two")

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.

Use parentheses to ensure the desired precedence . For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.

If both operands for the & , | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer.

If the operand for the ~ operator is a string, the operation will be performed on the ASCII values of the characters that make up the string and the result will be a string, otherwise the operand and the result will be treated as integers.

Both operands and the result for the << and >> operators are always treated as integers.

PHP's error_reporting ini setting uses bitwise values, providing a real-world demonstration of turning bits off. To show all errors, except for notices, the php.ini file instructions say to use: E_ALL & ~E_NOTICE

This works by starting with E_ALL: 00000000000000000111011111111111 Then taking the value of E_NOTICE... 00000000000000000000000000001000 ... and inverting it via ~ : 11111111111111111111111111110111 Finally, it uses AND (&) to find the bits turned on in both values: 00000000000000000111011111110111

Another way to accomplish that is using XOR ( ^ ) to find bits that are on in only one value or the other: E_ALL ^ E_NOTICE

error_reporting can also be used to demonstrate turning bits on. The way to show just errors and recoverable errors is: E_ERROR | E_RECOVERABLE_ERROR

This process combines E_ERROR 00000000000000000000000000000001 and 00000000000000000001000000000000 using the OR ( | ) operator to get the bits turned on in either value: 00000000000000000001000000000001

Example #1 Bitwise AND, OR and XOR operations on integers

The above example will output:

Example #2 Bitwise XOR operations on strings

Example #3 Bit shifting on integers

Output of the above example on 32 bit machines:

Output of the above example on 64 bit machines:

Shifting integers by values greater than or equal to the system long integer width results in undefined behavior. In other words, don't shift more than 31 bits on a 32-bit system, and don't shift more than 63 bits on a 64-bit system.

Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX .

See also pack , unpack , gmp_and , gmp_or , gmp_xor , gmp_testbit , gmp_clrbit

PHP Tutorial

Php advanced, mysql database, php examples, php reference, php operators.

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Increment/Decrement operators
  • Logical operators
  • String operators
  • Array operators
  • Conditional assignment operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result Try it
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power

PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.

Assignment Same as... Description Try it
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus

Advertisement

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result Try it
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Same as... Description Try it
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result Try it
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result Try it
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result Try it
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result Try it
?: Ternary $x = ? : Returns the value of $x.
The value of $x is if = TRUE.
The value of $x is if = FALSE
?? Null coalescing $x = ?? Returns the value of $x.
The value of $x is if exists, and is not NULL.
If does not exist, or is NULL, the value of $x is .
Introduced in PHP 7

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • PHP Tutorial
  • PHP Exercises
  • PHP Calendar
  • PHP Filesystem
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP IntlChar
  • PHP Image Processing
  • PHP Formatter
  • Web Technology

PHP Operators

In this article, we will see how to use the operators in PHP, & various available operators along with understanding their implementation through the examples.

Operators are used to performing operations on some values. In other words, we can describe operators as something that takes some values, performs some operation on them, and gives a result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1 and 2, performs an addition operation on them to give 3. 

Just like any other programming language, PHP also supports various types of operations like arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc), Increment/Decrement Operations, etc. Thus, PHP provides us with many operators to perform such operations on various operands or variables, or values. These operators are nothing but symbols needed to perform operations of various types. Given below are the various groups of operators:

  • Arithmetic Operators
  • Logical or Relational Operators
  • Comparison Operators
  • Conditional or Ternary Operators
  • Assignment Operators
  • Spaceship Operators (Introduced in PHP 7)
  • Array Operators
  • Increment/Decrement Operators
  • String Operators

Let us now learn about each of these operators in detail.

Arithmetic Operators: 

The arithmetic operators are used to perform simple mathematical operations like addition, subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax and operations in PHP.

+

Addition

$x + $y

Sum the operands

Subtraction

$x – $y

Differences the operands

*

Multiplication

$x * $y

Product of the operands

/

Division

$x / $y

The quotient of the operands

**

Exponentiation

$x ** $y

$x raised to the power $y

%

Modulus

$x % $y

The remainder of the operands

Note : The exponentiation has been introduced in PHP 5.6. 

Example : This example explains the arithmetic operator in PHP.

Logical or Relational Operators:

These are basically used to operate with conditional statements and expressions. Conditional statements are based on conditions. Also, a condition can either be met or cannot be met so the result of a conditional statement can either be true or false. Here are the logical operators along with their syntax and operations in PHP.

andLogical AND$x and $yTrue if both the operands are true else false
orLogical OR$x or $yTrue if either of the operands is true else false
xorLogical XOR$x xor $yTrue if either of the operands is true and false if both are true
&&Logical AND$x && $yTrue if both the operands are true else false
||Logical OR$x || $yTrue if either of the operands is true else false
!Logical NOT!$xTrue if $x is false

Example : This example describes the logical & relational operator in PHP.

Comparison Operators: These operators are used to compare two elements and outputs the result in boolean form. Here are the comparison operators along with their syntax and operations in PHP.

OperatorNameSyntaxOperation
==Equal To$x == $yReturns True if both the operands are equal
!=Not Equal To$x != $yReturns True if both the operands are not equal
<>Not Equal To$x <> $yReturns True if both the operands are unequal
===Identical$x === $yReturns True if both the operands are equal and are of the same type
!==Not Identical$x == $yReturns True if both the operands are unequal and are of different types
<Less Than$x < $yReturns True if $x is less than $y
>Greater Than$x > $yReturns True if $x is greater than $y
<=Less Than or Equal To$x <= $yReturns True if $x is less than or equal to $y
>=Greater Than or Equal To$x >= $yReturns True if $x is greater than or equal to $y

Example : This example describes the comparison operator in PHP.

Conditional or Ternary Operators :

These operators are used to compare two values and take either of the results simultaneously, depending on whether the outcome is TRUE or FALSE. These are also used as a shorthand notation for if…else statement that we will read in the article on decision making. 

Here, the condition will either evaluate as true or false. If the condition evaluates to True, then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

?:

Ternary

If the condition is true? then $x : or else $y. This means that if the condition is true then the left result of the colon is accepted otherwise the result is on right.

Example : This example describes the Conditional or Ternary operators in PHP.

Assignment Operators: These operators are used to assign values to different variables, with or without mid-operations. Here are the assignment operators along with their syntax and operations, that PHP provides for the operations.

=

Assign

$x = $y

Operand on the left obtains the value of the operand on the right

+=

Add then Assign

$x += $y

Simple Addition same as $x = $x + $y

-=

Subtract then Assign

$x -= $y

Simple subtraction same as $x = $x – $y

*=

Multiply then Assign

$x *= $y

Simple product same as $x = $x * $y

/=

Divide then Assign (quotient)

$x /= $y

Simple division same as $x = $x / $y

%=

Divide then Assign (remainder)

$x %= $y

Simple division same as $x = $x % $y

Example : This example describes the assignment operator in PHP.

Array Operators: These operators are used in the case of arrays. Here are the array operators along with their syntax and operations, that PHP provides for the array operation.

+

Union

$x + $y

Union of both i.e., $x and $y

==

Equality

$x == $y

Returns true if both has same key-value pair

!=

Inequality

$x != $y

Returns True if both are unequal

===

Identity

$x === $y

Returns True if both have the same key-value pair in the same order and of the same type

!==

Non-Identity

$x !== $y

Returns True if both are not identical to each other

<>

Inequality

$x <> $y

Returns True if both are unequal

Example : This example describes the array operation in PHP.

Increment/Decrement Operators: These are called the unary operators as they work on single operands. These are used to increment or decrement values.

++Pre-Increment++$xFirst increments $x by one, then return $x
Pre-Decrement–$xFirst decrements $x by one, then return $x
++Post-Increment$x++First returns $x, then increment it by one
Post-Decrement$x–First returns $x, then decrement it by one

Example : This example describes the Increment/Decrement operators in PHP. 

String Operators: This operator is used for the concatenation of 2 or more strings using the concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to append the argument on the right side to the argument on the left side.

.Concatenation$x.$yConcatenated $x and $y
.=Concatenation and assignment$x.=$yFirst concatenates then assigns, same as $x = $x.$y

Example : This example describes the string operator in PHP.

Spaceship Operators :

PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship operator or combined comparison operator is denoted by “<=>“. These operators are used to compare values but instead of returning the boolean results, it returns integer values. If both the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left operand is greater, it returns 1. The following table shows how it works in detail:

$x < $y$x <=> $yIdentical to -1 (right is greater)
$x > $y$x <=> $yIdentical to 1 (left is greater)
$x <= $y$x <=> $yIdentical to -1 (right is greater) or identical to 0 (if both are equal)
$x >= $y$x <=> $yIdentical to 1 (if left is greater) or identical to 0 (if both are equal)
$x == $y$x <=> $yIdentical to 0 (both are equal)
$x != $y$x <=> $yNot Identical to 0

Example : This example illustrates the use of the spaceship operator in PHP.

Please Login to comment...

Similar reads.

  • Web Technologies
  • PHP-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • ▼PHP Operators
  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Bitwise Operators
  • String Operators
  • Array Operators
  • Incrementing Decrementing Operators

PHP Assignment Operators

Description.

Assignment operators allow writing a value to a variable . The first operand must be a variable and the basic assignment operator is "=". The value of an assignment expression is the final value assigned to the variable. In addition to the regular assignment operator "=", several other assignment operators are composites of an operator followed by an equal sign.

Interestingly all five arithmetic operators have corresponding assignment operators, Here is the list.

The following table discussed more details of the said assignment operators.

Shorthand Expression Description
$a+= $b $a = $a + $b Adds 2 numbers and assigns the result to the first.
$a-= $b $a = $a -$b Subtracts 2 numbers and assigns the result to the first.
$a*= $b $a = $a*$b Multiplies 2 numbers and assigns the result to the first.
$a/= $b $a = $a/$b Divides 2 numbers and assigns the result to the first.
$a%= $b $a = $a%$b Computes the modulus of 2 numbers and assigns the result to the first.

View the example in the browser

Previous: Logical Operators Next: Bitwise Operators

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Bitwise operators in PHP

Are in PHP the single | and the keyword OR equivalent?

Analogously, are the single & and the keyword AND equivalent?

  • bitwise-operators

user402843's user avatar

  • 3 No , the word operators are logical operators, not bitwise operators, so they'll work a bit differently. –  aynber Commented Mar 23, 2022 at 18:11
  • 1 stackoverflow.com/questions/2376348/… has a bit more information. The previous link shows that AND and OR have a lower precedence than && and || , but work the same –  aynber Commented Mar 23, 2022 at 18:14
  • Does this answer your question? Difference between & and && in PHP –  Abel Masila Commented Mar 25, 2022 at 10:34

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

Your answer.

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Browse other questions tagged php bitwise-operators or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Suitable tool bag for vintage centre pull brake bike
  • Rock paper scissor game in Javascript
  • Can a Promethean's transmutation dramatic failure be used to benefit the Promethean?
  • Automatically closing a water valve after a few minutes
  • I stopped an interview because I couldn't solve some difficult problems involving technology I haven't used in years. What could I have done instead?
  • Do space stations have anything that big spacecraft (such as the Space Shuttle and SpaceX Starship) don't have?
  • How can one design earplugs so that they provide protection from loud noises, such as explosions or gunfire, while still allowing user to hear voices?
  • efficiently reverse EISH to HSIE
  • Tensor algebra and universal enveloping algebra
  • Energy and force, the basic formula
  • Embedding rank of finite groups and quotients
  • Strategies for handling Maternity leave the last two weeks of the semester
  • What was I thinking when I drew this diagram?
  • Does full erase create all 0s or all 1s on the CD-RW?
  • Can you cast a non-cantrip spell using your action, and make a bonus action melee spell attack on the same turn?
  • To "Add Connector" or not to "Add Connector", that is a question
  • Why are random fields based on topological spaces?
  • Automotive Controller LDO Failures
  • Large scale structure/Single galaxy simulation on GPU
  • Sci-fi/horror anthology TV episode featuring a man and a woman waking up and restarting events repeatedly
  • Sums of X*Y chunks of the nonnegative integers
  • Different Results of the Same GAM model depends on "discrete = TRUE"
  • How can the Word be God and be with God simultaneously without creating the meaning of two Gods?
  • What does it mean to echo multiple strings into a UNIX pipe?

bitwise assignment operators php

IMAGES

  1. Bitwise Operators in PHP

    bitwise assignment operators php

  2. PHP Bitwise Operators

    bitwise assignment operators php

  3. JavaScript Operators.

    bitwise assignment operators php

  4. PHP Bitwise Operators

    bitwise assignment operators php

  5. Programming Logic : Basic Operators

    bitwise assignment operators php

  6. PHP Bitwise Operators

    bitwise assignment operators php

COMMENTS

  1. PHP: Bitwise

    12 years ago. The NOT or complement operator ( ~ ) and negative binary numbers can be confusing. ~2 = -3 because you use the formula ~x = -x - 1 The bitwise complement of a decimal number is the negation of the number minus 1. NOTE: just using 4 bits here for the examples below but in reality PHP uses 32 bits.

  2. PHP

    The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then calculation is performed on the operands. The mathematical operations such as addition , subtraction , multiplication etc. can be performed at bit-level for faster processing. In PHP, the operators that works at ...

  3. PHP: Bitwise

    PHP's error_reporting ini setting uses bitwise values, providing a real-world demonstration of turning bits off. To show all errors, except for notices, the php.ini file instructions say to use: E_ALL & ~E_NOTICE

  4. PHP: Assignment

    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:

  5. PHP Bitwise AND assignment operator

    The Bitwise AND assignment operator (&=) assigns the first operand a value equal to the result of Bitwise AND operation of two operands. (x &= y) is equivalent to (x = x & y) The Bitwise AND operator (&) is a binary operator which takes two bit patterns of equal length and performs the logical AND operation on each pair of corresponding bits.

  6. PHP Bitwise Operators

    A bit ( B inary dig IT) is the basic unit of information stored in the computing system that exists in two possible states, represented as ON or OFF. In a computer system, the ON state considered as 1 and OFF state considered as 0. These states can be compared with two states of a flip-flop, two states of an electric switch ( ON and OFF) e.t.c.

  7. PHP Bitwise Operators: Binary Numbers

    The Bitwise NOT operator (~) is a unary operator that is used to perform bitwise negation on the individual bits of an integer. In PHP, the Bitwise NOT operator is represented by the tilde symbol (~). When the Bitwise NOT operator is applied to an integer, it flips each bit of the binary representation of that integer, changing 0s to 1s and 1s ...

  8. Understanding Bitwise Operators with PHP

    Tuesday, Oct 13, 2021. Oleg Charnyshevich. @OCharnyshevich. In this tutorial, you will learn about all 6 bitwise operators in PHP programming with examples. In the arithmetic-logic unit (within the CPU), mathematical operations like addition, subtraction, multiplication, and division are done at the bit level.

  9. PHP Bitwise Operators Tutorial : Code2care

    Output. 2. We can perform operations of bits (binary 0s and 1s) using Bitwise operators.Bitwise Opearators are AND, OR, EXCLUSIVE OR, NOT, Shift Left, Shift Right. PHP Tutorials and Lessons : Code2care.

  10. php

    Bitwise operators are used when you want to perform operations on a bit-by-bit basis on the underlying binary representations of integers. e.g. (5 & 3) == 7 . As others have suggested, there's usually not a lot of call for this in the sort of application that tends to get written in PHP (although there is in lower-level languages, like C).

  11. PHP Bitwise XOR and assignment operator

    The Bitwise XOR operator (^) is a binary operator which takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. It returns 1 if only one of the bits is 1, else returns 0. The example below describes how bitwise XOR operator works: 50 -> 110010 (In Binary) ^ 25 -> ^ 011001 (In ...

  12. PHP: Bitwise Operators

    Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions

  13. PHP Manual: Bitwise Operators

    Assignment Operators. Comparison Operators. Operators. PHP Manual. Bitwise Operators. Bitwise operators allow evaluation and manipulation of specific bits within an integer. ... Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX.

  14. bit manipulation

    Problems with PHP bitwise & operator. 1. Bitwise ~ Operator. 0. PHP, bitwise operations. 1. How does the &-bitwise operator work? 4. Bitwise operations on boolean values. 0. Bitwise OR operator in PHP, Bug or Feature? Hot Network Questions Assuming the Collatz conjecture is false, what is known about the size of the false set?

  15. PHP Bitwise OR and assignment operator

    The Bitwise OR and assignment operator (|=) assigns the first operand a value equal to the result of Bitwise OR operation of two operands. The Bitwise OR operator (|) is a binary operator which takes two bit patterns of equal length and performs the logical OR operation on each pair of corresponding bits. It returns 1 if either or both bits at ...

  16. PHP Operators

    PHP Assignment Operators. The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.

  17. php

    The ^ operator performs an XOR on the bit values of each variable. XOR does the following: a = 1100. b = 1010. xor = 0110. x is the result of the XOR operation. If the bits are equal the result is 0 if they are different the result is 1. In your example the ^= performs XOR and assignment, and you swap the bits around between the two variables ...

  18. PHP Operators

    The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then calculation is performed on the operands. ... In PHP, the '=' operator is used for assignment, while the '==' operator is used for loose equality comparison, meaning it checks if two values are equal without ...

  19. PHP assignment operators

    Description. Assignment operators allow writing a value to a variable. The first operand must be a variable and the basic assignment operator is "=". The value of an assignment expression is the final value assigned to the variable. In addition to the regular assignment operator "=", several other assignment operators are composites of an ...

  20. php

    This is called the two's complement arithmetic. You can read about it in more detail here. The operator ~ is a binary negation operator (as opposed to boolean negation), and being that, it inverses all the bits of its operand. The result is a negative number in two's complement arithmetic. edited Feb 3, 2012 at 14:07.

  21. Bitwise operators in PHP

    No, the word operators are logical operators, not bitwise operators, so they'll work a bit differently. - aynber. Commented Mar 23, 2022 at 18:11. 1. ... Problems with PHP bitwise & operator. 1 Bitwise ~ Operator. 4 bitwise operator in PHP. 0 PHP, bitwise operations. 4 ...