strpos in PHP works in a different way. If you are used to Java then it will come as no surprise that you will have your head scratching into confusion why it does not give the correct output.

So far in the strpos PHP page, contributors gave their own versions of strpos. The most accurate and the function that worked the way I wanted it to the same way that indexOf works in Java is by contributor teddanzig@yahoo.com.

This is his function.

Languages like Java and Javascript provide a method called indexOf() that returns an int of the first position of the string key found in a string. strpos() in PHP acts differently. If it finds the substring within the string, it returns an int value of the position of the substring. If it does not, it returns a boolean instead.

I find this stupid. It would have been easier if it still returned an int value like the usual -1 to indicate it didn’t find any substring inside the string.

To do an if statement using strpos() of PHP just like this Java code:

Do this in PHP:

Notice the 2 equal sign succeeding after the exclamation point? That line checks if the statement is false. If you wish to change it to a true condition statement, just put in 3 equal signs.

Related Posts Plugin for WordPress, Blogger...