BLOG // July 13, 2021

Goodbye strpos and strstr: str_contains in PHP8

The frustration of having to use strpos and strstr to check if strings contain another string is over with PHP 8 and a great new string function called str_contains.

It's a very efficient method to check if a needle is in a haystack, as you can see below:

$haystack = 'My long string containing a needle in it.';
if (str_contains($haystack, 'needle')) {
    //
}

Something that's not often noticed is that functions like strstr are quite slow comparatively, and str_contains is much faster. The performance between str_contains and strpos interestingly is very similar, but from a code quality point of view it's much more sensible to use str_contains.

Comments

Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.