Simple if statement returning unexpected results |
[eluser]Lone[/eluser]
Ok so right now I feel like a complete noob asking this but can someone explain why the following happens in an if statement in PHP (the third snippet)... Its probably something simple I am missing but just want to see exactly what it is. A string is treated as 'true' which is expected Code: $test1 = true; The number 0 is treated as 'false' which is expected Code: $test1 = false; So if 0 is meant to be 'false' and a string is 'true' then why does the below statement get treated as true? Code: $test1 = 0;
[eluser]John_Betong[/eluser]
Hi Lone, I have been tripped up with similar problems and often think that the loose type declarations are a bigger problem than having strict types similar to 'C'. From the Php Manual: Converting to Boolean Code: To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
[eluser]Lone[/eluser]
Thanks for that John_Betong but looking at what you have posted it shows that the results I am seeing are still unexpected. Quote:the following values are considered FALSE: Quote:Every other value is considered TRUE Therefore in my last sample $test1 should be false and $test2 should be true meaning the IF statement should not echo yes.
[eluser]xwero[/eluser]
I think it has to do with the weak typing in php. That why the === operator is useful. If you do Code: $test1 = 0; I read something similar not so long ago with the explanation of similar behavior but i can't find it at the moment.
[eluser]wiredesignz[/eluser]
xwero is correct regarding typing and zero should not be considered as false. ie: finding a character position in a string may return 0, meaning first position, false means not found. There is a subtle difference.
[eluser]Lone[/eluser]
Thanks for the explanations and suggestions - never seen the === operator before but certainly handy for a situation like above where type needs to be checked. Certainly something for us to look out for down the track!
[eluser]John_Betong[/eluser]
I looked again in the PHP Manual for Comparison Operators and found this explanation and example: Quote: $a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
[eluser]Derek Jones[/eluser]
We cover this a bit with some examples in our developer guidelines for ExpressionEngine, and this page of the PHP documentation has nifty charts showing the difference between loose and strict comparisons. PHP's type juggling is actually rather handy, though a developer needs to be fully aware of what's going on. |
Welcome Guest, Not a member yet? Register Sign In |