PHP Tip: String Position Returns 0

Follow @tristarweb

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!

About James

Hello there, I'm James. I studied Multimedia Design at university. I'm a designer at heart, though I love developing innovative and exciting solutions to web based products.I now specialise in front end web design and bespoke Wordpress powered websites.

3 Responses to PHP Tip: String Position Returns 0

  1. ICT Quotes says:

    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!

  2. Software Design Development says:

    05:34 12/02/2011

    Thanks for your valuable tip………

  3. Website Maintenance says:

    10:56 12/02/2011

    It is very informative. Thanks a lot for sharing it.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please wrap all source code with [code][/code] tags.

Follow Tristar on Twitter