Difference between strpos and stripos in PHP

In PHP, finding the position of a substring within a string is a common task, primarily achieved using the strpos() and stripos() functions. This article explains the key differences between these two functions, specifically focusing on case sensitivity, and provides clear examples and best practices to help you choose the right one for your PHP projects.

The Core Difference: Case Sensitivity

The fundamental difference between strpos() and stripos() is how they handle uppercase and lowercase letters:

How They Work

Both functions search a string (the “haystack”) for a specific substring (the “needle”) and return the numerical position of the first occurrence.

The index of the first character in a string is 0 (not 1). If the substring is not found, both functions return false.

Syntax

strpos(string $haystack, string $needle, int $offset = 0): int|false
stripos(string $haystack, string $needle, int $offset = 0): int|false

Code Examples

Example 1: Using strpos() (Case-Sensitive)

Because strpos() is case-sensitive, searching for “world” in “Hello World” will fail.

$haystack = "Hello World";

$pos1 = strpos($haystack, "World"); // Returns 6
$pos2 = strpos($haystack, "world"); // Returns false

Example 2: Using stripos() (Case-Insensitive)

Because stripos() is case-insensitive, both “World” and “world” will successfully find the match at index 6.

$haystack = "Hello World";

$pos1 = stripos($haystack, "World"); // Returns 6
$pos2 = stripos($haystack, "world"); // Returns 6

Important Best Practice: Strict Comparison

Because these functions can return 0 (if the substring is found at the very beginning of the string) or false (if the substring is not found), you must use strict comparison operators (=== or !==) to evaluate the results.

Using loose comparison (== or !=) will lead to bugs, as PHP treats 0 as false.

Incorrect Way:

$string = "Apple pie";
// "Apple" is at index 0. This condition will incorrectly evaluate to false.
if (strpos($string, "Apple") == false) {
    echo "Not found"; 
}

Correct Way:

$string = "Apple pie";

if (strpos($string, "Apple") === false) {
    echo "Not found";
} else {
    echo "Found!";
}

Summary Comparison

Feature strpos() stripos()
Case Sensitivity Case-sensitive Case-insensitive
Return Value (Success) Integer (0 or higher) Integer (0 or higher)
Return Value (Failure) false false
Performance Slightly faster Slightly slower (due to case conversion)