I’ve long used assignment inside long if statements to simplify things. But in this case, it’s not working as intended. Here’s what I’ve got:
$Employee = GetEmployeeName($Record['employee_id']);
echo 'First name: '.$Employee['first_name'];
echo 'Last name: '.$Employee['last_name'];
echo 'Record first name: '.$Record['first_name'];
echo 'Record last name: '.$Record['last_name'];
echo 'Comparing first name: ';
var_dump(strcasecmp($Employee['first_name'], $Record['first_name']));
echo 'Comparing last name: ';
var_dump(strcasecmp($Employee['last_name'], $Record['last_name']));
echo 'Comparing both together: ';
var_dump(strcasecmp($Employee['first_name'], $Record['first_name'])
|| strcasecmp($Employee['last_name'], $Record['last_name']));
echo 'All together now: ';
var_dump($Foo = GetEmployeeName($Record['employee_id'])
&& (strcasecmp($Foo['first_name'], $Record['first_name'])
|| strcasecmp($Foo['last_name'], $Record['last_name'])));
Here’s the results:
First name: ZACHARY
Last name: TAYLOR
Record first name: Zachary
Record last name: Taylor
Comparing first name: int(0)
Comparing last name: int(0)
Comparing both together: bool(false)
All together now: bool(true)
This makes no sense. Comparing the first name resolves as 0 (false); comparing the last name resolves as 0 (false); comparing them together resolves as false. Yet when I add the assignment into the if, it suddenly resolves as true. I’ve been assigning variables in ifs for a long time and I’ve never seen this happen. The weird thing is, if I assign outside the if, it works fine. So I could do that, but at this point it’s about the principle of finding out what’s going wrong so I can improve my knowledge of the language.
Assignment in this case gives true, as you can see by the fact that $Employee is populated. So, the final var_dump is essentially “true && false”, which should resolve as false. Right?
The boolean operator
&&has a higher precedence than the assignment operator=. So this:Is equivalent to:
Put the parentheses around the assignment and it works: