PHP:
$a = 2;
$b = 3;
if($b=1 && $a=5)
{
$a++;
$b++;
}
echo $a.'-'.$b;
$a = 2;
$b = 3;
if($a=5 and $b=1)
{
$a++;
$b++;
}
echo $a.'-'.$b;
Output 6-16-2
.I don't understand the 1
here.
Perl :
$a = 2;
$b = 3;
if($b=1 && $a=5)
{
$a++;
$b++;
}
print $a.'-'.$b;
$a = 2;
$b = 3;
if($a=5 and $b=1)
{
$a++;
$b++;
}
print $a.'-'.$b;
Output 6-66-2
, I don't understand the second 6
here.
Anyone knows the reason?
Actually I know &&
has higher precedence than and
,but I still has the doubt when knowing this before hand.
UPDATE
Now I understand the PHP one,what about the Perl one?
Regarding Perl:
Unlike PHP (but like Python, JavaScript, etc.) the boolean operators don't return a boolean value but the value that made the expression true (or the last value) determines the final result of the expression† (source).
$b=1 && $a=5
is evaluated as
$b = (1 && $a=5) // same as in PHP
which is the same as $b = (1 && 5)
(assignment "returns" the assigned value) and assigns 5
to $b
.
The bottom line is: The operator precedence is the same in Perl and PHP (at least in this case), but they differ in what value is returned by the boolean operators.
FWIW, PHP's operator precedence can be found here.
What's more interesting (at least this was new to me) is that PHP does not perform type conversion for the increment/decrement operators.
So if $b
is true
, then $b++
leaves the value as true
, while e.g. $b += 1
assigns 2
to $b
.
†: What I mean with this is that it returns the first (leftmost) value which
false
in case of &&
true
in case of ||
or the last value of the expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With