Javatpoint Logo
Javatpoint Logo

PHP String substr_compare() Function

The substr_compare() is a built-in function of PHP, which helps to compare the two strings from a specified start position to specified end position. This function is a binary-safe function and optionally case-sensitive. PHP 5 and above versions support this function.

Syntax

The syntax of substr_compare() function is given below.

It consists of five parameters in which three are mandatory, and the remaining two are optional. Below is the description for these parameters:

Parameters

$main_str (required): It is the main string parameter of this function which needs to be compared. It is a mandatory parameter.

$str (required): It is the second string parameter of this function which is specified to be compared. It is also a mandatory parameter as main_str.

$start_pos (required): It is a mandatory parameter, which has an integer value. This parameter specifies the value, where to start a comparison of $str in $main_str. In other words, - it provides the start position for the comparison.

If the passed value is negative, then it starts comparing from the end of the string.

$length (optional): This parameter is not mandatory to pass in this function. It consists the length of the comparison, means it specifies how much of $str to compare.

$case-insensitivity (optional): This parameter contains the Boolean value, which specifies whether to perform case-sensitive comparison or not. It is an optional parameter as $length. If case-insensitivity is TRUE, then the comparison will be case-insensitive.

  • FALSE -Case-sensitive (default value)
  • TRUE - Case-insensitive

Return Values

This function returns the following values:

Return 0 - If both the given strings are equal.

Return < 0 - If $main_str (from start position) is less than $str.

Return > 0 - If $main _str (from start position) is greater than $str.

Note: If $length parameter value is equal and greater than the length of the main string ($main_str), then this function displays a warning and will return FALSE.

Changelog

Version Description
PHP 5.1.0 It is possible to use a negative start_pos.
PHP 5.5.11 $length can be 0 now.
PHP 7.2.18, 7.3.5 $start_pos may be equal to the length of main string ($main_str).

Examples

Below few numbers of examples are given to learn the working of substr_compare() function.

Example 1

In the below example, we are passing 3 mandatory parameters in this function. Lets's see the working of substr_compare() with three arguments.

Output:

0
11
-5

Example 2

Output:

11		
0		
-1

Example 3

Output:

0		
1		
-1

Example 4: Case-sensitive/insensitive

In the below example, we are passing all the five parameters in this function. Lets's see the working of substr_compare() with all arguments.

Output:

0		
1		
0	





Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA