PHP strrchr() Function: Description, Parameters, Return Value, and Usage Examples

The article explains PHP's strrchr() function, detailing its syntax, parameter behavior, return values, and provides two practical code examples demonstrating how to retrieve the last occurrence of a character or substring within a string.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP strrchr() Function: Description, Parameters, Return Value, and Usage Examples

The strrchr() function in PHP searches for the last occurrence of a specified character (or the first character of a string) within a given haystack string and returns the portion of the haystack starting from that position to the end.

Syntax: string strrchr(string $haystack, mixed $needle) Return value: If the needle is found, the function returns the substring from the needle's last occurrence to the end of the haystack; otherwise it returns FALSE.

Parameters:

haystack : The string to be searched.

needle : If a string, only its first character is used; if not a string, it is converted to an integer and treated as an ASCII value.

Example 1:

<?php
echo strrchr("Hello world!", 101);
echo "
\r";
// Get the last line content
$text = "Line 1
Line 2
Line 3";
$last = substr(strrchr($text, 10), 1);
echo $last;
?>

This example demonstrates retrieving the substring after the last newline character (ASCII 10) in a multi‑line string.

Example 2:

<?php
echo strrchr("Hello world! What a beautiful day!", What);
?>

The second example shows using a string as the needle, where only the first character of the needle ("W") is considered, returning the portion of the haystack from the last "W" onward.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendstring-functionscode-snippetphp-examplestrrchr
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.