PHP में | (Bitwise OR) और || (Logical OR) मौलिक रूप से अलग operations करते हैं।
| - Bitwise OR Operator
प्रत्येक bit position पर operate करता है। यदि किसी भी operand में bit 1 है, तो result में 1 सेट होता है।
<?php $x = 1; // Binary: 0001 $y = 2; // Binary: 0010 $result = $x | $y; // Binary: 0011 = Decimal 3 echo "$x | $y = $result"; // Output: 1 | 2 = 3 // Bitwise breakdown: // 0001 (1) // | 0010 (2) // = 0011 (3)
|| - Logical OR Operator
पूरे operands को boolean values के रूप में evaluate करता है। Short-circuit evaluation करता है।
<?php $x = 1; // Truthy $y = 2; // Truthy $result = $x || $y; // Boolean true = 1 (when echoed) echo "$x || $y = $result"; // Output: 1 || 2 = 1 // Logical evaluation: // $x is truthy → short-circuit → return true (1) // $y is never evaluated
Side-by-Side Comparison
| Expression | | (Bitwise) | || (Logical) |
|---|---|---|
1 | 2 | 3 (0011) | 1 (true) |
0 | 5 | 5 | 1 (true) |
0 | 0 | 0 | 0 (false) |
5 || 0 | 5 | 1 (true) |
'' || 'hello' | Error (string पर bitwise नहीं) | 1 (true) |
व्यावहारिक उपयोग मामले
Bitwise OR (|) - Flags/Permissions के लिए
<?php
// Permission flags
const READ = 1; // 0001
const WRITE = 2; // 0010
const EXECUTE = 4; // 0100
const ADMIN = 8; // 1000
// Permissions combine करें
$userPerms = READ | WRITE; // 0011 = 3
$adminPerms = READ | WRITE | EXECUTE | ADMIN; // 1111 = 15
// Check permission
function hasPermission($userPerms, $required) {
return ($userPerms & $required) === $required;
}
echo hasPermission($userPerms, READ) ? 'हाँ' : 'नहीं'; // हाँ
echo hasPermission($userPerms, ADMIN) ? 'हाँ' : 'नहीं'; // नहीं
Logical OR (||) - Conditional Logic के लिए
<?php
// Default values (null coalescing operator ?? बेहतर है PHP 7+ में)
$name = $inputName || 'Guest'; // PHP में यह काम नहीं करता जैसा JS में
// सही PHP तरीका:
$name = $inputName ?: 'Guest'; // Elvis operator (PHP 5.3+)
$name = $inputName ?? 'Guest'; // Null coalescing (PHP 7+)
// Short-circuit evaluation - second operand नहीं चलता यदि first truthy
$result = expensiveCheck() || fallback(); // यदि expensiveCheck() truthy, fallback() नहीं चलता
// Function calls में
function getConfig($key) {
return $_ENV[$key] ?? config($key) ?? 'default';
}
महत्वपूर्ण अंतर सारांश
| विशेषता | | Bitwise OR | || Logical OR |
|---|---|---|
| Operand types | Integers | Any (boolean context में convert) |
| Operation | Bit-level | Boolean logic |
| Short-circuit | नहीं | हाँ |
| Return type | Integer | Boolean (echo में 1/0) |
| Use case | Flags, masks, permissions | Conditions, defaults, control flow |