Earlier today, a web design colleague and I came across a problem with our strpos function in PHP. Take the following situation for example:
<?php $string = "abcdefgh"; $find = "abcd"; $strpos = strpos($string, $find); if($strpos) { echo "Found it!"; } else { echo "Not Found!"; } ?>
Although “abcd” is clearly in the string, the strpos function will still echo “Not Found!”. This is because it is found at position 0, which is treated as NULL by PHP.
By using type casting, I can tell PHP to treat the returned value of the strpos function as an integer, and not NULL:
<?php $string = "abcdefgh"; $find = "abcd"; $strpos = strpos($string, $find); if($strpos || $strpos === (int)0) { echo "Found it!"; } else { echo "Not Found!"; } ?>
This function will now echo “Found it!”, which is exactly what we wanted! we are saying:
If strpos is TRUE, or strpos is equal to the integer 0 – echo “Found it!”.
Anyway, I hope this helps someone as it had us fairly stumped earlier!
18:43 11/02/2011
A very informative post indeed with a lot of useful info. i hope i’ll find other posts like this in the future. Thanks!
05:34 12/02/2011
Thanks for your valuable tip………
10:56 12/02/2011
It is very informative. Thanks a lot for sharing it.