strchr() 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.

In PHP, the `strchr()` function is used to find the first occurrence of a character in a string and return the rest of the string starting from that character. It’s similar to the `strstr()` function, but `strchr()` has its parameters reversed.

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

<?php
strchr(string $haystack, mixed $needle, bool $before_needle = false): string|false
?>

1. `$haystack`: The string to search in.
2. `$needle`: The character or substring to search for. If it’s a string, only the first character is used.
3. `$before_needle` (optional): If set to true, `strchr()` returns the part of the haystack before the first occurrence of the needle.

Now, let’s see an example of how to use the `strchr()` function:

<?php
$str = "Hello, world!";
$char = "o";
$result = strchr($str, $char);
if ($result !== false) {
echo "First occurrence of '$char' found: $result";
} else {
echo "Character '$char' not found in the string.";
}
?>

In this example, we have a string `$str` containing “Hello, world!”. We’re searching for the first occurrence of the character “o” using `strchr()`. If the character is found, `$result` will contain the substring starting from the first occurrence of “o” till the end of the string. We then check if `$result` is not false, and if so, we print out the found substring. Otherwise, we print a message indicating that the character was not found in the string.