Current Location: Home> Latest Articles> How to determine whether the return value of the scripos function in PHP is false? Common misunderstandings and correct usage methods

How to determine whether the return value of the scripos function in PHP is false? Common misunderstandings and correct usage methods

M66 2025-05-13

In PHP, the stripos() function is used to find where a string first appears in another string (case insensitive). This function is often used when processing string-related logic, such as determining whether a keyword exists in a given content.

However, due to the return value characteristic of stripos() , many developers are prone to stumble when making judgments, especially for processing the return value of 0 . This article will analyze this issue in detail and give a correct way of judgment.

1. Basic usage of the stripos() function

 $haystack = "Welcome to m66.net!";
$needle = "welcome";

$pos = stripos($haystack, $needle);

In the example above, stripos() will return 0 because "welcome" appears at the beginning of the target string (though case is different, stripos() is case-insensitive).

2. Common misunderstandings: Use if directly to judge

Many beginners will write this way:

 if (stripos($haystack, $needle)) {
    echo "Found the keyword";
} else {
    echo "Keywords do not exist";
}

The problem with this code is that if the keyword appears at the beginning of the string (position is 0), if judgment will treat 0 as false , and the else branch is incorrectly executed .

3. Correct way of judgment: all equal to false

 $pos = stripos($haystack, $needle);
if ($pos !== false) {
    echo "Found the keyword,Location is:$pos";
} else {
    echo "Keywords do not exist";
}

Using the writing method that is equal to ( !== false ) can accurately distinguish whether the function returns 0 or false , thereby avoiding logical errors.

4. Examples of application scenarios

For example, we want to detect whether the comments submitted by a user contain certain sensitive words and give a reminder: