Home > Backend Development > PHP Tutorial > Why Does Comparing `strpos()` to `true` Fail to Detect String Occurrences in PHP?

Why Does Comparing `strpos()` to `true` Fail to Detect String Occurrences in PHP?

Susan Sarandon
Release: 2024-12-10 08:29:10
Original
338 people have browsed it

Why Does Comparing `strpos()` to `true` Fail to Detect String Occurrences in PHP?

Misinterpreting Strictly Comparing strpos() against true

In attempting to determine whether a string contains an undesirable element, programmers may encounter unexpected results when utilizing strpos() for direct equality comparisons.

Consider this scenario:

$link = 'https://google.com';
$unacceptables = ['https:','.doc','.pdf', '.jpg', '.jpeg', '.gif', '.bmp', '.png'];

foreach ($unacceptables as $unacceptable) {
    if (strpos($link, $unacceptable) === true) {
        echo 'Unacceptable Found<br />';
    } else {
        echo 'Acceptable!<br />';
    }
}
Copy after login

Intriguingly, this code prints "Acceptable!" for each element in $unacceptables, despite https being present in $link. This seemingly paradoxical behavior arises from the nature of strpos() itself.

Delving into the official PHP documentation clarifies the function's true purpose:

Returns the numeric position of the first occurrence of needle in the haystack string.

Therefore, when comparing the result of strpos() directly against true, you effectively check for the existence of the undesirable element in $link, not its equality with true.

To rectify this issue, a more appropriate approach is to utilize !== false in the if statement:

// ...
if (strpos($link, $unacceptable) !== false) {
Copy after login

By doing so, you correctly assess whether strpos() has detected the presence of the undesirable element, resulting in the desired outcome.

The above is the detailed content of Why Does Comparing `strpos()` to `true` Fail to Detect String Occurrences in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template