PHP: Equal and the Same Type
by , 07-11-2008 at 12:00 AM (2089 Views)
PHP offers the ability to create conditional statements that compare against the same value and the same type. This means that you can test a string variable against another variable and determine if it is a string and if it holds the same value. Using this method means a string of "10" and an integer of 10 will not be the same. In PHP a variables type is determined by the context in which the
variable is used which makes variable types interchangeable (meaning a variable can be a string, integer, float, etc. without specifically changing the type). Because of this it is necessary to test again value and type in certain conditions.
Take a look at this PHP example:In the above script $myString equals "Hello WebmasterTalkForums" while the conditional statement executes strpos with the needle value of "H". Since "H" is the first indice of the string "Hello WebmasterTalkForums" the return value is 0 (0 is the first indice of a numerical array) . Because PHP automatically converts 0 to a boolean value of false the condition is never met (even though "H" does exist in the string"). A simple way to get around this is to test against type and value:PHP Code:$myString = "Hello WebmasterTalkForums";if (strpos($myString, "H")) { echo "Never Executed! ";}echo "End of Script.... Goodbye.";
The code above tests the return value of strpos (which is numerical or FALSE) against a boolean value of false. It tests against type and value.PHP Code:$myString = "Hello WebmasterTalkForums";if (strpos($myString, "H") !== false) { print "Is Executed! ";}echo "End of Script.... Goodbye.";
In this example the return value is (int) 0 which is, in PHP, normally converted to false. Since the types are different (integer and boolean) this statement evaluates to true ( int 0 does not equal boolean false).













Email Blog Entry