strstr() and strpos()

I have seen a lot of people who are using strstr when in fact they should be using strpos. It is better to use strpos if all you want to know is if a string exists (true/false). strstr() will return the actual string from the first occurance of $needle to the end of the string which causes more resources to be used since it has to be parsed out. strpos will return the integer index for the position of the first occurance, in this case int(44). Try out this code example.

PHP:
  1. $string = 'this is just an example for you';
  2. $needle = 'an example';
  3.  
  4. echo strstr( $string, $needle).';
  5. var_dump(strpos($string, $needle));

As you can see strstr will require more processing and more time than strpos if you are using it a lot. The best thing to do is evaluate the situation. If you just need to know true/false, always use strpos. However if you will need to use the value found in $needle then you will have to use strstr. Just keep in mind that the larger and larger an application get's the more you have to watch out for these mishaps :)



Uncategorized.

Have your say...

You must be logged in to post a comment.

Technology Blogs Add to Technorati Favorites Page Rank Tool NYPHP Users Group View Joseph Crawford's profile on LinkedIn

   

SEO Consultant SEO services
11 visitors online now
2 guests, 9 bots, 0 members
Max visitors today: 12 at 12:27 am UTC
This month: 22 at 09-03-2010 02:06 am UTC
This year: 51 at 02-24-2010 03:06 pm UTC
All time: 51 at 02-24-2010 03:06 pm UTC