Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 147 ยท Operators

Bitwise, String, Array and Pipe Operators

Learn PHP's remaining operators - bitwise flags, array union and comparison, instanceof, why to avoid @, the PHP 8.5 pipe operator |> and the full precedence table.

You've met the operators you'll use on almost every line: arithmetic and assignment, comparison, logical and the null coalescing and ternary family. This lesson rounds out the set with the ones that show up in more specific situations.

Bitwise operators pack several yes/no options into one integer, which is how PHP's own flags like JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES work. Array operators merge and compare arrays. instanceof checks what kind of object you have. The error suppression operator @ hides warnings, and you'll learn why that's usually a bad idea. Finally, PHP 8.5's pipe operator |> lets you write a series of transformations from left to right. The lesson ends with the complete precedence table, so you can look up how any expression is grouped.

Bitwise operators

An integer is stored as a row of bits (binary digits). Bitwise operators work on those bits one position at a time:

Operator Name Result bit is 1 whenโ€ฆ
$a & $b AND both bits are 1
$a | $b OR either bit is 1
$a ^ $b XOR exactly one bit is 1
~$a NOT the bit was 0 (every bit flips)
$a << $n shift left bits move $n places left (multiply by 2โฟ)
$a >> $n shift right bits move $n places right (divide by 2โฟ, rounding down)

The easiest way to understand them is to print the bits. sprintf('%04b', $n) formats a number in binary, padded to four digits:

PHP Seeing the bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

~5 is -6, not some small positive number: integers are 64-bit and signed, so flipping every bit of 5 also flips the sign bit. Right shifts keep the sign, which is why -16 >> 2 is -4. Shifting by a negative amount throws an ArithmeticError, and shifting by 64 or more gives 0 (or -1 for negative numbers with >>).

Flags: many switches in one integer

The main practical use of bitwise operators in PHP is flags. Give each option its own bit (1, 2, 4, 8, โ€ฆ), and one integer can hold any combination:

  • combine options with |
  • test an option with &
  • turn an option off with & ~
  • toggle an option with ^
PHP Permission flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The if ($permissions & READ) tests work because & returns either 0 (falsy) or the flag's value (truthy). To require several flags at once, compare the masked result with the full set, as the last two lines do: a user with all three permissions passes, and a user without DELETE fails. The extra parentheses are required, for a reason you'll see in the precedence table below.

You use exactly this pattern with PHP's own functions:

PHP
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
error_reporting(E_ALL & ~E_DEPRECATED);   // everything except deprecations

You'll meet those flags in JSON and Errors, Warnings and Notices.

Note: Bitwise operators also work on two strings, combining them byte by byte, so 'a' | 'b' is not an error. That's almost never what you want. If you see bitwise operators applied to strings, it's usually a bug caused by a value that should have been an integer. Cast with (int) first.

String operators

PHP has only two string operators, both covered in Arithmetic and Assignment Operators: . joins two strings, and .= appends to a variable. One detail matters for the precedence table: since PHP 8, . binds more loosely than + and -, so 'Total: ' . $a + $b adds first and then concatenates.

Array operators

Several operators also work on arrays:

Operator Meaning
$a + $b union: all of $a, plus the elements of $b whose keys $a doesn't have
$a == $b same key/value pairs (loose comparison, any order)
$a === $b same key/value pairs, same order, same types
$a != $b, $a <> $b not ==
$a !== $b not ===

The union operator is the one that surprises people. It never overwrites: when both arrays have the same key, the left value wins. That makes it a neat way to apply defaults, and a trap when you expected it to append lists:

PHP Array union and comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line is true because PHP casts the string key '1' to the integer 1 when it builds the array, so both arrays really are identical. The full key-casting rules are in Associative Arrays, and Array Functions compares + with array_merge() in detail.

instanceof

$value instanceof ClassName returns true if $value is an object of that class, of a class that extends it, or of a class that implements that interface. For anything that isn't an object, it simply returns false:

PHP Checking types with instanceof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

instanceof binds more tightly than !, so !$rex instanceof Car means !($rex instanceof Car). Many teams still add the parentheses because it reads more clearly. You'll use instanceof a lot once you reach Inheritance and Abstract Classes and Interfaces. In code with type declarations you need it less, because PHP checks parameter types for you.

The error suppression operator @ (avoid it)

Putting @ in front of an expression hides any warnings or notices that expression produces:

PHP
$text = @file_get_contents('settings.txt');   // no warning if the file is missing

It looks convenient, but the problem doesn't go away: the function still fails and returns false, and now nobody gets told why. Bugs that would have shown up as a clear warning turn into mysterious behavior later. @ also has a run-time cost, and in PHP 8 it no longer hides fatal errors at all.

PHP What @ hides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The honest alternatives are checking before you act (as above), using functions that return a clear failure value, and turning errors into exceptions, all covered in Errors, Warnings and Notices and Reading and Writing Files. If you ever do need @ (a few old functions warn in situations you can't check in advance), use it on the smallest possible expression and handle the failure right after it.

Warning: PHP also has an execution operator: text inside backticks, like `ls -l`, runs as a shell command, just like shell_exec(). It's easy to mistake for a string, and passing user input into it is a command-injection hole. Don't use it; see Secure Coding Checklist.

The pipe operator |> (PHP 8.5)

Transforming a value in several steps usually means nesting calls, which you then read from the inside out:

PHP
$slug = strtolower(str_replace(' ', '-', trim($title)));

PHP 8.5 added the pipe operator |>. It passes the value on its left as the single argument to the callable on its right, so the same steps read in the order they happen:

PHP
$slug = $title |> trim(...) |> (fn($s) => str_replace(' ', '-', $s)) |> strtolower(...);

The right side must be a callable that takes one argument. The usual ways to write one are:

  • first-class callable syntax, trim(...), which turns a function into a callable (covered in Anonymous Functions and Closures)
  • an arrow function in parentheses, (fn($x) => ...), when you need extra arguments
  • any other callable value, such as a closure stored in a variable or an invokable object
PHP Building a slug with the pipe operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A few rules to know:

  • Arrow functions must be wrapped in parentheses. Without them, the arrow function would swallow every pipe after it, so PHP refuses to compile 5 |> fn($x) => $x * 2 and asks you to add them.
  • No by-reference parameters. Functions that modify their argument in place, such as sort(), can't be piped: $list |> sort(...) throws an Error saying the argument "could not be passed by reference". Pipes are for functions that return a new value.
  • Precedence sits between concatenation and comparison. Arithmetic and . happen before the pipe, and ==, < and friends happen after, so 'a' . 'b' |> strtoupper(...) gives 'AB', and $x |> f(...) == 10 compares the piped result.

Pipes shine for short chains of pure transformations: cleaning a string, or processing an array with the functional array functions. For steps with side effects, or when you need intermediate values for debugging, plain variables are still clearer.

Operator precedence

Precedence decides how PHP groups an expression when you don't add parentheses, and associativity decides the grouping among operators on the same level. Here is the full table, from highest (grouped first) to lowest:

Operators Associativity Notes
clone new n/a
** right 2 ** 3 ** 2 is 2 ** 9
++ -- ~ - + (unary), casts like (int), @ n/a
instanceof left
! n/a
* / % left
+ - left
<< >> left
. left lower than +/- since PHP 8
|> left PHP 8.5
< <= > >= non-associative
== != === !== <> <=> non-associative
& left
^ left
| left
&& left
|| left
?? right
? : non-associative nesting needs parentheses
= += -= .= ??= and other assignments right
yield from yield print n/a
and left
xor left
or left

Two rows deserve a second look. The bitwise operators &, ^ and | sit below the comparisons, so $flags & READ == READ means $flags & (READ == READ), which is not what you meant. Write ($flags & READ) === READ. And the word operators and, or and xor sit below assignment, which is the trap explained in Logical Operators.

PHP Precedence surprises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You don't need to memorize the table. Remember the handful of surprises shown here, and whenever an expression mixes operator families, add parentheses. They cost nothing and make the grouping obvious to the next reader.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does echo 6 & 3; print?

    6 is 110 and 3 is 011 in binary. AND keeps only the bits set in both, 010, which is 2.
  2. 2. Given $perm = READ | WRITE; with READ = 1 and WRITE = 2, which statement removes WRITE and keeps everything else?

    ~WRITE has every bit set except WRITE's, so ANDing with it clears that one bit and leaves the others unchanged.
  3. 3. What is ['a', 'b'] + ['x', 'y', 'z']?

    Union keeps every key of the left array and only adds keys it doesn't have. Keys 0 and 1 exist on the left, so only key 2 ('z') is added.
  4. 4. Why does $list |> sort(...) fail in PHP 8.5?

    The pipe passes a value, not a variable, so functions that modify their argument in place throw an Error. Use functions that return a new value.
  5. 5. What is the main problem with writing $data = @json_decode(@file_get_contents($path));?

    @ only hides diagnostics. The functions still fail and return false or null, and the reason is lost. Check for failures explicitly instead.

Summary

  • Bitwise operators & | ^ ~ << >> work on the bits of integers. Their main use is flags: combine with |, test with &, clear with & ~, toggle with ^.
  • Bitwise &, ^ and | bind more loosely than comparisons: write ($flags & X) === X.
  • . and .= are the only string operators; . is lower than + and - since PHP 8.
  • The array union + keeps the left array's values for duplicate keys and only adds missing keys; == compares pairs in any order, === also checks order and types.
  • instanceof checks an object's class, parent classes and interfaces, and returns false for non-objects.
  • The @ operator hides warnings without fixing anything; check for failures explicitly. Never use backtick shell execution.
  • The pipe operator |> (PHP 8.5) passes a value into a one-argument callable: use func(...) or a parenthesized arrow function, and no by-reference functions.
  • When in doubt about precedence, add parentheses.

Next: if, elseif and else