PHP 8 reference · String Functions

PHP strpos() Function

Find the position of the first occurrence of a substring. Returns false if it's not found, so compare with === false.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
haystack The string to search in.
needle The string to find.
offset optional Where to start searching; negative counts from the end. Default: 0

Return value

The position (from 0), or false.

Examples

Find a characterTry it yourself
<?php
$email = "[email protected]";
$at = strpos($email, "@");
echo $at, "\n";
echo substr($email, $at + 1), "\n";

Output

3
example.com
Always check with !== falseTry it yourself
<?php
$pos = strpos("camel", "c");
if ($pos !== false) {
    echo "found at $pos\n"; // 0 is a valid position
}
var_dump(strpos("camel", "z"));

Output

found at 0
bool(false)

Common mistakes

  • if (strpos($s, "a")) fails when the match is at position 0. Compare with !== false, or use str_contains() (PHP 8+) when you only need yes or no.

Version history

VersionChange
PHP 4.0Added
PHP 8.0An empty needle is allowed (it matches at the offset) instead of raising a warning.

In other languages

Was this page helpful?