1

I have simple code

$value = 5;
$string = 'Abc';

var_dump(($value > 0) || (strlen($string) == 2));
var_dump(($value > 0) | (strlen($string) == 2));

Only what is changed is type of returned value (first is boolean, second int). There is another difference between | and ||? Can I change one to another?

Live test: http://sandbox.onlinephpfunctions.com/code/548ab723cbd156be70a596978427fbd73ce4639f

ventaquil
  • 2,780
  • 3
  • 23
  • 48
  • 6
    One (`|`) is a [bitwise operator](http://www.php.net/manual/en/language.operators.bitwise.php), the other (`||`) is a [logical operator](http://www.php.net/manual/en/language.operators.logical.php).... and no, they're not interchangeable in the same way that using `+` and `*` with two numbers won't generally give you the same result because they're different operators that do different things – Mark Baker Nov 20 '15 at 09:52
  • No you can't change one to another. They're completely different operations. – Jonnix Nov 20 '15 at 09:52
  • @MarkBaker but logic is only 1 bit value. There is true (1) and false (0). `1 | 0 <=> 1 || 0` - yes or not? – ventaquil Nov 20 '15 at 09:55
  • 2
    @ventaquil - logical works with Booleans, correct; and if you compare two non-Booleans using a logical operator, they're cast to Booleans first.... so what's the point you're trying to make? Are you suggesting that because Booleans are represented as 1-bit, then a bitwise operator should work the same way? No! a bitwise operator works on __every__ individual bit that comprises the data being operated on; a logical operator works on a single bit – Mark Baker Nov 20 '15 at 09:56
  • @MarkBaker okay I forget about it :) I know everything now, thank You. – ventaquil Nov 20 '15 at 09:59

1 Answers1

5

var_dump(($value > 0) || (strlen($string) == 2));

|| is a logical logical operatpor, see http://php.net/manual/de/language.operators.logical.php

var_dump(($value > 0) | (strlen($string) == 2));

| is a bitwise operator, see http://php.net/manual/de/language.operators.bitwise.php

Sure, you can change | to ||, but you won't get the same result ;) A little explanation for your code, but you should really read the doc for bit- and logical operators:

You already answered, that both don't do the same:

var_dump(($value < 0) || (strlen($string) == 2)); -> returns a boolean true

var_dump(($value < 0) | (strlen($string) == 2)); -> returns an integer 1

If you do:

var_dump(true === 1);

You will get false, because integer 1 isn't a boolean true, even if:

var_dump(true == 1);

or

var_dump(true === (bool)1);

will return true (== doesn't check for type, see the docs, and (bool) casts the integer 1 to be a boolean true (see http://php.net/manual/de/language.types.boolean.php#language.types.boolean.casting to know what is false and what is true).

Florian
  • 2,796
  • 1
  • 15
  • 25