Current Location: Home> Latest Articles> How to elegantly handle the situation where the scripos search fails in PHP and returns false?

How to elegantly handle the situation where the scripos search fails in PHP and returns false?

M66 2025-05-13

In PHP, stripos() is a very common function to find the first occurrence of a string in another string, insensitively. If found, stripos() returns an integer indicating the starting position of the matching string in the target string; if not found, false is returned.

Here comes the problem: since the return is " 0 or false ", it is easy to make errors in the conditional judgment.

Let me give you a common pitfall:

 if (stripos($haystack, $needle)) {
    echo "Found!";
} else {
    echo "Not found!";
}

If $needle is at the beginning of $haystack (position 0), stripos() returns 0 , and if (0) will be treated as false, resulting in "not found" output, logical error!

The correct way to judge

To gracefully handle the situation where stripos() returns false , we should clearly determine whether it is false , rather than a simple Boolean judgment:

 $pos = stripos($haystack, $needle);
if ($pos !== false) {
    echo "Found,In location:$pos";
} else {
    echo "Not found!";
}

By using the congruent comparison symbol !== , we can accurately distinguish 0 and false .

A further package: Write a gadget function

To make the code clearer and reusable, we can encapsulate a helper function:

 function containsIgnoreCase($haystack, $needle) {
    return stripos($haystack, $needle) !== false;
}

// Example of usage
if (containsIgnoreCase("https://m66.net/news", "NEWS")) {
    echo "Include keywords!";
} else {
    echo "不Include keywords!";
}

This way, writing code is easy to read and reduces repetitive logic, making it very suitable for widespread use in projects.

Practical application: determine whether the user's access source contains certain keywords

Suppose we need to determine whether the URL the user access contains utm_source :