Home > Backend Development > PHP Tutorial > Why Does Strict Equality with `strpos()` in PHP Often Produce Unexpected Results?

Why Does Strict Equality with `strpos()` in PHP Often Produce Unexpected Results?

Susan Sarandon
Release: 2024-12-16 15:18:20
Original
195 people have browsed it

Why Does Strict Equality with `strpos()` in PHP Often Produce Unexpected Results?

Unreliable Boolean Comparison in PHP: Understanding the Quirks of strpos()

In PHP, the strpos() function is a fundamental tool for searching within strings. However, a common pitfall that programmers encounter involves comparing the result of strpos() using the strict equality operator (===) against true.

The Issue:

Consider the following code snippet:

$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

This code attempts to check whether the $link URL contains any of the strings listed in $unacceptables. However, it unexpectedly prints "Acceptable!" for all cases, even when "https:" is present in $link.

The Solution:

The root of the issue lies in PHP's behavior for comparing the result of strpos(). By default, strpos() returns an integer representing the position of the first occurrence of the substring within the string. If the substring is not found, it returns false.

In the code snippet, when comparing strpos() against true, you're essentially checking if the result is a number other than zero. Since the function always returns a number when it finds a match, this comparison always returns true, incorrectly indicating the presence of a substring.

To resolve this, use the strict inequality operator (!==) instead, which checks for non-equality. This ensures that the comparison is made against false when the substring is not found.

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

By following this simple modification, the code snippet will correctly identify and print "Unacceptable Found" when the $link URL contains one of the prohibited substrings.

The above is the detailed content of Why Does Strict Equality with `strpos()` in PHP Often Produce Unexpected Results?. 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