Difference between the | and || or operator in php

In PHP, | and || are both OR operators but operate at different levels. | is a bitwise OR that works on individual bits of integer values, while || is a logical OR that works on boolean truth values of complete operands.

| (Bitwise OR Operator)

The | operator compares each bit of two integers and sets the resulting bit to 1 if either corresponding bit is 1. It returns an integer result.

  1 in binary:  0 0 0 1
  2 in binary:  0 0 1 0
  ?????????????????????
  1 | 2 result: 0 0 1 1  ?  3

|| (Logical OR Operator)

The || operator evaluates the truth value of its operands as a whole. It returns true (which echoes as 1) if either operand is truthy, and false if both are falsy. It also uses short-circuit evaluation − if the left operand is truthy, the right operand is not evaluated.

Key Differences

Feature | (Bitwise OR) || (Logical OR)
Operates On Individual bits of integers Boolean truth values
Returns Integer Boolean (true/false)
Short-Circuit No (always evaluates both sides) Yes (skips right if left is truthy)
1 __ 2 3 (0001 | 0010 = 0011) true (echoes as 1)
0 __ 0 0 false

Example

The following example demonstrates both operators ?

<?php
    $x = 1;  // binary: 0001
    $y = 2;  // binary: 0010

    // Bitwise OR: compares bits
    echo '$x | $y = ';
    echo ($x | $y);       // 0001 | 0010 = 0011 = 3
    echo "
"; // Logical OR: checks truth values echo '$x || $y = '; echo ($x || $y); // true || true = true (echoes as 1) echo "
"; // Difference is clear with larger numbers $a = 5; // binary: 0101 $b = 3; // binary: 0011 echo '$a | $b = '; echo ($a | $b); // 0101 | 0011 = 0111 = 7 echo "
"; echo '$a || $b = '; echo ($a || $b); // true || true = true (1) echo "
"; // With zero values echo '0 | 0 = '; echo (0 | 0); // 0 echo "
"; echo '0 || 0 = '; var_dump(0 || 0); // bool(false) ?>

The output of the above code is ?

$x | $y = 3
$x || $y = 1
$a | $b = 7
$a || $b = 1
0 | 0 = 0
0 || 0 = bool(false)

Conclusion

| is a bitwise operator that compares individual bits and returns an integer. || is a logical operator that evaluates truth values and returns a boolean. Use | for bit manipulation (flags, permissions) and || for conditional logic (if statements, boolean expressions).

Updated on: 2026-03-14T12:35:50+05:30

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements