0
0
PhpHow-ToBeginner · 3 min read

How to Use strpos in PHP: Syntax, Examples, and Tips

In PHP, strpos is used to find the position of the first occurrence of a substring inside another string. It returns the zero-based index if found, or false if the substring is not present.
📐

Syntax

The strpos function has three parameters:

  • haystack: The string to search in.
  • needle: The substring to find.
  • offset (optional): The position to start searching from.

It returns the position of the first match or false if not found.

php
int|false strpos(string $haystack, string $needle, int $offset = 0)
💻

Example

This example shows how to find the position of the word "world" in a string. It prints the position if found or a message if not.

php
<?php
$text = "Hello world!";
$pos = strpos($text, "world");

if ($pos !== false) {
    echo "Found 'world' at position: $pos";
} else {
    echo "'world' not found.";
}
?>
Output
Found 'world' at position: 6
⚠️

Common Pitfalls

A common mistake is to check strpos with == false instead of === false. Since strpos can return 0 (start of string), using == false treats 0 as false and gives wrong results.

Always use !== false or === false to check the result correctly.

php
<?php
// Wrong way
$pos = strpos("apple", "a");
if ($pos == false) {
    echo "Not found";
} else {
    echo "Found at $pos";
}

// Right way
$pos = strpos("apple", "a");
if ($pos === false) {
    echo "Not found";
} else {
    echo "Found at $pos";
}
?>
Output
Not foundFound at 0
📊

Quick Reference

ParameterDescription
$haystackThe string to search in
$needleThe substring to find
$offset (optional)Start position for search (default 0)
ReturnPosition of first occurrence or false if not found

Key Takeaways

Use strpos to find the first position of a substring inside a string in PHP.
Check the result with strict comparison (=== false) to avoid errors when position is 0.
The function returns zero-based index or false if substring is missing.
You can specify an optional offset to start searching from a different position.