- 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.
- 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.
- 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.
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.
Similarly, you need to obtain the binary representation of $b for the final calculation, as illustrated in the following figure.
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.
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:
- $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 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.
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?
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
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
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:
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
- 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_1 | Bit_2 | Bit_1 ^ Bit_2 |
---|---|---|
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 0 |
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:
- 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.
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 TutorialPhp 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:
PHP Arithmetic OperatorsThe PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.
PHP Assignment OperatorsThe 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.
Advertisement PHP Comparison OperatorsThe PHP comparison operators are used to compare two values (number or string):
PHP Increment / Decrement OperatorsThe PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to decrement a variable's value.
PHP Logical OperatorsThe PHP logical operators are used to combine conditional statements.
PHP String OperatorsPHP has two operators that are specially designed for strings.
PHP Array OperatorsThe PHP array operators are used to compare arrays.
PHP Conditional Assignment OperatorsThe PHP conditional assignment operators are used to set a value depending on conditions:
COLOR PICKERContact SalesIf you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected] Report ErrorIf you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected] Top TutorialsTop references, top examples, get certified.
PHP OperatorsIn 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:
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.
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.
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.
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.
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.
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.
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.
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.
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:
Example : This example illustrates the use of the spaceship operator in PHP. Please Login to comment...Similar reads.
Improve your Coding Skills with PracticeWhat kind of Experience do you want to share?
PHP Assignment OperatorsDescription. 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.
View the example in the browser Previous: Logical Operators Next: Bitwise Operators Follow us on Facebook and Twitter for latest update.
Collectives™ on Stack OverflowFind 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 PHPAre in PHP the single | and the keyword OR equivalent? Analogously, are the single & and the keyword AND equivalent?
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 inPost 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 .
Hot Network Questions
|
IMAGES
COMMENTS
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.
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 ...
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
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:
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.
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.
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 ...
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.
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.
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).
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 ...
Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions
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.
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?
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 ...
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.
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 ...
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 ...
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 ...
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.
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 ...