Open In App

What is the difference between the | and || or operator in PHP?

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we explain the difference between the single '|' and double '||' OR operators in PHP. You'll learn their distinct behaviors in conditional statements and their impact on code execution and performance.

PHP '|' Operator

It is a bitwise OR operator. This operator is used to set the bits of operands if either a or b or both are set. It means the value of the bit will be set to 1.

ABA | B
000
011
101
111

Syntax:

$a | $b

Example 1:

In this example, the bitwise OR operator '|' is used to compare the integers 3 and 10. The bitwise OR operation combines their binary representations: 3 (which is 0011 in binary) and 10 (which is 1010 in binary). The result of 3 | 10 is 11, derived from the bitwise OR of these binary values.

php
<?php
$a = 3;
$b = 10;
echo $a | $b;
?>

Output
11

Explanation:

In above example, given two values, a = 3 and b = 10. Then convert both the numbers into binary number i.e a = 0011 and b = 1010. Apply OR (|) operation and compute the value of $a | $b.

PHP '||' Operator

This is the logical OR operator. This operator is used to do the OR operation. If either of the bits will be 1, then the value of OR will be 1.

Syntax:

$a || $b

Example 2:

In this example, the logical OR operator '||' is used in a conditional statement. It checks if $a equals 3 or $b equals 0. If either condition is true, it outputs 1; otherwise, it outputs 0.

php
<?php
$a = 3;
$b = 10;
if($a = 3 || $b = 0)
    echo '1';
else
    echo '0';
?>

Output
1

Explanation:

Here the values for the variables are set. Check if either of the condition is true or not, since the value of a in the if statement is true as it is set to be 3, the OR operator will execute to be true and '1' will be displayed.

Note:

The key difference in the working of the two operators and the nature are same. The bitwise OR operator sets the bit value whereas the logical OR operator sets true or 1 if either one of the conditions/bit value is 1 else it sets false or 0.


Similar Reads