1.2.1166. Strpos()-like Comparison

The result of that function may be mistaken with an error.

strpos(), along with several PHP native functions, returns a string position, starting at 0, or false, in case of failure. It is recommended to check the result of strpos() with === or !==, so as to avoid confusing 0 and false.

This analyzer list all the strpos()-like functions that are directly compared with == or !=. preg_match(), when its first argument is a literal, is omitted : this function only returns NULL in case of regex error.

The full list is the following : * array_search() * collator_compare() * collator_get_sort_key() * current() * fgetc() * file_get_contents() * file_put_contents() * fread() * iconv_strpos() * iconv_strrpos() * imagecolorallocate() * imagecolorallocatealpha() * mb_strlen() * next() * pcntl_getpriority() * preg_match() * prev() * readdir() * stripos() * strpos() * strripos() * strrpos() * strtok() * curl_exec()

In PHP 8.0, str_contains() will do the expected job of strpos(), with less confusion.

<?php

// This is the best comparison
if (strpos($string, 'a') === false) { }

// This is OK, as 2 won't be mistaken with false
if (strpos($string, 'a') == 2) { }

// strpos is one of the 26 functions that may behave this way
if (preg_match($regex, $string)) { }

// This works like above, catching the value for later reuse
if ($a = strpos($string, 'a')) { }

// This misses the case where 'a' is the first char of the string
if (strpos($string, 'a')) { }

// This misses the case where 'a' is the first char of the string, just like above
if (strpos($string, 'a') == 0) { }

?>

See also strpos not working correctly.

1.2.1166.1. Suggestions

  • Use identity comparisons, for 0 values : === instead of ==, etc.

  • Compare with other exact values than 0 : strpos() == 2

  • Use str_contains()

1.2.1166.2. Specs

Short name

Structures/StrposCompare

Rulesets

All, Analyze, CE, CI-checks, PHP recommendations, Top10

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Features

strict-comparison

ClearPHP

strict-comparisons

Examples

Piwigo, Thelia

Available in

Entreprise Edition, Community Edition, Exakat Cloud