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

`substr_compare()` is a PHP function used to compare parts of two strings. It allows you to compare substrings of two given strings starting from a specified position and up to a specified length. This function returns 0 if the substrings are equal, a negative value if the substring of the first string is less than the substring of the second string, and a positive value if the substring of the first string is greater than the substring of the second string.

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

<?php
substr_compare(string $main_str, string $str, int $offset, ?int $length = null, bool $case_insensitive = false): int
?>

Now, let’s see an example of how you can use `substr_compare()`:

<?php
$str1 = "Hello World";
$str2 = "Hello";
$result = substr_compare($str1, $str2, 0, strlen($str2));
if ($result === 0) {
echo "The substrings are equal.";
} elseif ($result < 0) {
echo "The substring in str1 is less than str2.";
} else {
echo "The substring in str1 is greater than str2.";
}
?>

In this example, we compare the substring `$str2` with the beginning of `$str1`. The `substr_compare()` function returns 0 since both substrings are equal. Therefore, the output will be “The substrings are equal.”