What is the strpos() function in PHP?

Share

Overview

The strpos() method in PHP checks for the position of a string in another string. A string known as the $haystack value will be searched to find another value, $needle, inside it. For the strpos() method to evaluate as true and return the position of $needle in $haystack, the $needle value has to be a character or a set of characters that must be found in $haystack. Otherwise, it returns false.

Syntax

strpos($haystack,$needle, $offset)
  • $haystack: This is the value that will contain the $needle value.

  • $needle: This is a set of characters or a single character that may or may not be available in $haystack.

  • $offset: This parameter is zero by default. It determines the position in $haystack from which the search of $needle should start. If the offset is negative, the search will start from the end of the $haystack.

Return value

  • If the $needle is found in the $haystack, the return value will be the index position of the $needle in the $haystack.
  • If the $needle is not found in the $haystack, the Boolean value false will be returned.

Code

In the code snippet below, the strpos() method gets the position of the same string in another string:

<?php
$searchWord = 'pb';
$stringVal1 = 'ijk';
$stringVal2 = 'WASPBEE';
$valPos1 = stripos($stringVal1, $searchWord);
$valPos2 = stripos($stringVal2, $searchWord);
// surely, 'pb' is not in 'ijk'
if ($valPos1 === false) {
echo "The value " . $searchWord . " can't be found in " . $stringVal1 . "\n";
}
if ($valPos2 !== false) {
echo "we saw " . $searchWord ." in ". $stringVal2 . " at index ". $valPos2;
}
?>

Explanation

  • Line 2, 3, and 4: We declare the $searchWord, $stringVal1, and $stringVal2 variables.

  • Line 6 and 7: We use the strpos() function to find the position of some substrings in them.

  • Line 10, 11, and 12: We use the if statement to check what value is returned by the strpos() function, and if false executes the code in the block.

  • Line 14, 15, and 16: We use the if statement to check what value is returned by the strpos() function. If it is not false, it executes the code in the block.