OneBite.Dev - Coding blog in a bite size

Find The Last Occurrence Of A Character In A String In PHP

Code snippet for how to Find The Last Occurrence Of A Character In A String In PHP with sample and detail explanation

String manipulation is a fundamental and important aspect of any programming language. In PHP, we often encounter situations where we need to find the last occurrence of a character in a string. Today, we’ll discuss how to perform this task in PHP.

Code snippet for finding the last occurrence of a character in a string

$myString = 'Hello, dear developer. How are you today?';
$findMe   = 'o';
$lastOccurrence = strrpos($myString, $findMe); 
   
if ($lastOccurrence === false) { 
    echo 'Sorry, we couldn’t find your character.'; 
} else { 
    echo 'The last occurrence of "' . $findMe . '" is at position ' . $lastOccurrence; 
}

Code Explanation for finding the last occurrence of a character in a string

This PHP snippet will help us find the last occurrence of a character in a string.

First, we initialize the variable $myString with the string in which we’ll be searching. After that, $findMe is assigned the character we want to locate.

The strrpos() function is used to find the position of the last occurrence of the specified character in a string. This function takes two parameters: the string to search in and the character to search for. In our example, we’ve passed $myString as the first parameter and $findMe as the second. The strrpos() function returns the position of the last occurrence of the specified character if it is found, or false if it’s not found.

Finally, an if condition is used to check the result of the strrpos() function. If the result is false, it means the character was not found in the string, and a message is echoed to inform the user about it. If the result is not false, it means the character was found, and its last position is echoed.

The important part to note here is that string indexes start at 0 in PHP. So the first character of the string has position 0.

This simple PHP script will hence allow you to quickly and easily find the last occurrence of any character in your chosen string.

php