Reputation: 51
This is something weird that started happening recently.
function someFunction() {
return 0;
}
if (someFunction() == 0)
runCode();
elseif (someFunction() == '0')
runOtherCode();
In this situation runCode() will not be called but instead runOtherCode() will be called. Any reason why this is happening?
Edit: Using === fixed this error in some situations. However the other time this issue was present was when returning integer results from a database. For some reason the integers where being converted into strings but adding (int) to the data before returning the data fixed that error.
Upvotes: 0
Views: 38
Reputation: 1441
You need to use strict comparison to prevent type coercion. Basically like this:
if(someFunction() === 0)
elseif(someFunction() === '0')
3 equal signs instead of two invokes a strict comparison and is the only way to differentiate between string and integer comparison.
Edit: This is also relevant in other cases, so always consider it.
Upvotes: 1