String Functions

PHP substr_compare() Function

Topic: PHP String ReferencePrev|Next


The substr_compare() function compares two strings from a specified start position, up to a specified length of characters. The comparison is case-sensitive by default.

The following table summarizes the technical details of this function.

Return Value:

Returns a negative value (< 0) if main_str from start position is less than str; a positive value (> 0) if it is greater than str, and 0 if they are equal.

If start is set to a value greater than the length of main_str, or the length is set to a value less than 0, this function returns FALSE.
Changelog: Since PHP 7.3.5, the start may now be equal to the length of main_str.
Version: PHP 5+


The basic syntax of the substr_compare() function is given with:

substr_compare(main_str, str, start, length, case_insensitivity);

The following example shows the substr_compare() function in action.

// Sample strings
$main_str = "Blackbird";
$str = "bird";

// Comparing strings
echo substr_compare($main_str, $str, 5);


The substr_compare() function accepts the following parameters.

Parameter Description
main_str Required. Specifies the main string being compared.
str Required. Specifies the secondary string being compared.
start Required. Specifies the start position for the comparison. If it is negative, counting will start from the end of the string.
length Optional. Specifies the length of the comparison. The default value is the largest of the length of the str compared to the length of main_str minus the start.
case_insensitivity Optional. If set to true, the comparison will be case-insensitive. Default value is false which perform a case-sensitive comparison.

More Examples

Here're some more examples showing how substr_compare() function actually works:

The following example simply compares the two strings from the beginning.

// The two strings are equal
echo substr_compare("Blackbird", "Blackbird", 0)."<br>";

// The main string is greater than the secondary string
echo substr_compare("Blackbird", "Black", 0)."<br>";

// The main string is less than the secondary string
echo substr_compare("Black", "Blackbird", 0);

The following example demonstrates the usage of different parameters.

// Comparing strings
echo substr_compare("Blackbird", "Black", 0)."<br>";
echo substr_compare("Blackbird", "black", 0, 5, true)."<br>";
echo substr_compare("Blackbird", "bird", -4, 4)."<br>";
echo substr_compare("Blackbird", "bird", 2, 4)."<br>";
echo substr_compare("Blackbird", "lack", 1, 5);
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties