Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The &= operator is the bitwise AND assignment operator. It evaluates the binary representations of both operands, performs a bitwise AND operation on each corresponding pair of bits, and assigns the resulting value back to the left operand.
$a &= $b;
This is the shorthand equivalent of the expanded assignment syntax:
$a = $a & $b;

Mechanical Behavior

When the &= operator is executed, PHP compares the bits of the left operand against the bits of the right operand based on the following truth table:
  • 1 & 1 results in 1
  • 1 & 0 results in 0
  • 0 & 1 results in 0
  • 0 & 0 results in 0
Only bits that are set to 1 in both operands will remain 1 in the assigned result. All other bits are set to 0.

Integer Evaluation

When dealing with numeric values, PHP converts the operands to integers before performing the bitwise operation. Any fractional components in floating-point numbers are truncated.
$a = 14;  // Binary: 1110
$b = 11;  // Binary: 1011

$a &= $b; 

// Bitwise evaluation:
//   1110  ($a)
// & 1011  ($b)
// ---
//   1010  (Result assigned to $a)

echo $a; // Outputs: 10

Type Juggling and String Operands

PHP’s bitwise operators exhibit specific behavior depending on the data types of the operands:
  1. Integer and String: If one operand is an integer and the other is a string, the string must be a valid numeric string (e.g., "123"). PHP will implicitly cast the numeric string to an integer before performing the bitwise AND operation. As of PHP 8.0, attempting a bitwise operation between an integer and a non-numeric string throws a TypeError.
  2. String and String: If both operands are strings, the &= operator performs the bitwise AND operation against the ASCII values of the corresponding characters in each string. The length of the resulting string is determined by the length of the shorter string operand.
$str = "foo"; // ASCII: 102, 111, 111
$str &= "bar"; // ASCII:  98,  97, 114

// Evaluation per character:
// 'f' (102: 01100110) & 'b' (98:  01100010) = 'b' (98:  01100010)
// 'o' (111: 01101111) & 'a' (97:  01100001) = 'a' (97:  01100001)
// 'o' (111: 01101111) & 'r' (114: 01110010) = 'b' (98:  01100010)

echo $str; // Outputs: "bab"
Master PHP with Deep Grasping Methodology!Learn More