CodeBlanks Logo Icon CodeBlanks

Searching with strpos()

PHP course · Beginner · Lesson 90/116

Learn to find a substring's position with strpos() and its false return behavior.

Searching with strpos()

To find the position of a substring inside a string, use strpos(). It is called as strpos($haystack, $needle); it looks for $needle inside $haystack and returns the position of the first match. If nothing is found, it returns false.

Example: strpos('hello', 'l') returns 2 because the first 'l' is at position 2 (h=0, e=1, l=2). Positions start at zero.

The false pitfall

strpos() has an important pitfall: when the match is at the start of the string, it returns 0; when nothing is found, it returns false. The two are equal under loose comparison.

That is why if (strpos($text, $word)) is wrong: when the match is at position 0, the 0 is treated as false and the code behaves unexpectedly. The correct way is a strict comparison: if (strpos($text, $word) === false).

Exercise Search for a word in a sentence

Assign "PHP is a great language" to $sentence. Assign the result of strpos($sentence, 'great') to $pos. Initially assign "Missing" to $message. Then check with if ($pos !== false) and assign "Found" to $message. Finally print with echo $message;.

Show example solution
First assign $sentence, $pos and $message. Then write if ($pos !== false) { $message = 'Found'; }. Finally add echo $message;
Example solution:
<?php
$sentence = "PHP is a great language";
$pos = strpos($sentence, 'great');
$message = 'Missing';
if ($pos !== false) {
    $message = 'Found';
}
echo $message;

Test yourself

  1. What does strpos('hello', 'l') return?

    strpos('hello', 'l')
    • 2
    • 3
    • 0
    • false
    Show answer

    2 — Correct. The first 'l' is at position 2.

  2. Write a strict comparison

    if (strpos($text, $word) ____ false) {
        echo 'Not found';
    }
    Show answer
    if (strpos($text, $word) === false) {
        echo 'Not found';
    }
  3. Match each call to its result

    strpos('hello', 'l')
    2
    strpos('hello', 'z')
    false
    strpos('hello', 'h')
    0

All lessons in Beginner