1

PHP program

$x = (False or 123)
echo $x

python code

x= (False or 123)
print(x)

In php answer is 1 and in python answer is 123.

Why is that?

chris85
  • 23,846
  • 7
  • 34
  • 51
lahiruhashan
  • 120
  • 1
  • 11
  • In PHP, $x will be boolean true if either `False` or `123` equates to true, false if they are both false.... `False` is False, but `123` equates to True by loose typing, so $x will be boolean true.... and echoing a boolean true displays as `1`.... if you var_dumped instead, you'd see it as a boolean true – Mark Baker Oct 19 '17 at 14:26
  • what about python?? – lahiruhashan Oct 19 '17 at 14:55

2 Answers2

1

Python and and or do a "McCarthy evaluation" that returns the last value, see https://stackoverflow.com/a/22598675/196206 or Wikipedia.

PHP does also short circuit evaluation but only a boolean value is always returned: http://php.net/manual/en/language.operators.logical.php

Messa
  • 24,321
  • 6
  • 68
  • 92
  • Thank you for the answer but I am interested in the results that two code segments returns and I am looking for the reason behind the results. – lahiruhashan Oct 19 '17 at 14:36
-1

PHP: $x = (False or 123). False is false(!), 123 is true, false or true == true, so $x get true (or 1 when you print it.

Python: does or operation first, then assigns result to x. int(False) is 0, int(123) is 123, so it gets 123. In Python, there is a trick were the or return value is the value that made it true, and not the boolean result. See this page: http://www.diveintopython.net/power_of_introspection/and_or.html

Nic3500
  • 8,144
  • 10
  • 29
  • 40