Boolean assignment operators in PHP



PHP Snippet 1:

$foo = true;
$foo &= false;

if (!$foo) {
  echo 'Bitwise works!';
}

$bar = true;
$bar = $bar && false;

if (!$bar) {
  echo 'Boolean works!';
}

// Output: Bitwise works!Boolean works!

PHP Snippet 2:

<?php
$values = array(false, 0, 0.0, "", "0", array(), 12, "string", array(1));

foreach ($values as $value) {
    $bit_test = true;
    $bit_test &= $value;

    $bool_test = true;
    $bool_test = $bool_test && false;
    if ($bit_test != $bool_test) {
        echo 'Difference for: ';
        var_dump($value);
    }
}

// Output:
// Difference for: array(1) {
//  [0]=>
//  int(1)
// }

PHP Snippet 3:

function OrOp(&$booleanVar, $conditions)
{
    $booleanVar = $booleanVar && $conditions;
    return $booleanVar;
}

PHP Snippet 4:

$foo = $foo && false;

PHP Snippet 5:

OrOp($foo, false);

PHP Snippet 6:

OrOp($foo, $condition1 && $condition2 && $condition3);

PHP Snippet 7:

$a = true;
$a &= 10; // => returns 0 (false) because 1 & 10 = 0

PHP Snippet 8:

$a = true;
$a &&= 10; // => $a would be true