strrpos() Function in PHP 8.2 With Example

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

The `strrpos()` function in PHP is used to find the position of the last occurrence of a substring within a string. It searches for the last occurrence of a specified substring (needle) within a string (haystack). If the substring is found, `strrpos()` returns the position of the last occurrence of the substring in the haystack. If the substring is not found, it returns `false`.

Here’s the syntax of `strrpos()` function:

<?php
strrpos(string $haystack, string $needle, int $offset = 0): int|false
?>

1. `$haystack`: The string to search within.
2. `$needle`: The substring to search for.
3. `$offset` (optional): The position in the haystack to start searching from. If specified, searching starts from this position. If a negative offset is used, searching starts from the end of the string.

Now, let’s see an example of how to use `strrpos()` in PHP:

<?php
$string = "Hello world, hello PHP!";
$substring = "hello";

// Find the last occurrence of the substring in the string
$position = strrpos($string, $substring);

if ($position !== false) {
echo "Last occurrence of '$substring' found at position: $position";
} else {
echo "Substring '$substring' not found in the string.";
}
?>

Output:

Last occurrence of 'hello' found at position: 13

In this example, we’re searching for the last occurrence of the substring “hello” within the string “Hello world, hello PHP!”. The `strrpos()` function returns the position of the last occurrence, which is 13. We then check if the position is not `false` (indicating that the substring was found) and display the position accordingly.