Home > Backend Development > PHP Tutorial > Why Does strpos() Comparison with `=== true` Fail in PHP String Searches?

Why Does strpos() Comparison with `=== true` Fail in PHP String Searches?

Mary-Kate Olsen
Release: 2024-12-16 18:15:11
Original
228 people have browsed it

Why Does strpos() Comparison with `=== true` Fail in PHP String Searches?

Unintended Truth: Understanding the Mismatch in strpos() Comparisons

Despite its common use for string searches, the PHP function strpos() has an unconventional behavior when comparing its result to true. To understand this anomaly, let's examine a snippet of code:

$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

Surprisingly, this code prints "Acceptable!" for every element in the $unacceptables array, even though "https:" is present in the $link variable.

To unravel this puzzle, we must delve into the semantics of strpos(). As its documentation states, strpos() returns the "numeric position of the first occurrence" of the $unacceptable string within $link. In this case, strpos() finds "https:" at position 0 and returns 0, which is a truthy value in PHP.

Therefore, the condition in the if statement (strpos($link, $unacceptable) === true) evaluates to true every time because strpos() always returns a numeric position, which is always coerced to a boolean true.

To rectify this, we should use a non-strict comparison operator (!==):

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

By changing the comparison to "not equal to false," we ensure that the if statement only evaluates to true when strpos() finds a match and returns a non-zero value (i.e., any numeric position other than 0).

The above is the detailed content of Why Does strpos() Comparison with `=== true` Fail in PHP String Searches?. 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