Comparing Strings with strcmp()
function
PHP strcmp()
function: PHP offer a bit more than just comparing strings and returning true or false.
The strcmp()
function compares two strings and this comparison is case sensitive.
strcmp() prototype
int strcmp ( string $str1 , string $str2 )
This means that strcmp()
function accepts two string (comma separated) as input to compare and returns an int (integer).
See the following table to understand the above function definition in an easy way:
Function Part | Description |
---|---|
int | Type of value this function returns, which is an integer (int) |
strcmp | The function name |
string | First parameter type, this function accepts only string data type |
$str1 | First parameter names, variables that hold the data |
string | Second parameter type, this function accepts only string data type |
$str2 | Second parameter name, variables that hold the data |
Syntax
strcmp($str1, $str2)
Return values
The strcmp()
function returns:
- < 0 if
$str1
is less than$str2
- > 0 if
$str1
is greater than$str2
- 0 if
$str1
and$str2
are equal
Examples
Example 1
strcmp()
function returns a positive value (> 0)
when the string passed as the first parameter is greater than the second parameter, see example:
<?php
$str1 = 'b';
$str2 = 'a';
echo strcmp($str1,$str2); //prints 1 (which is > 0)
?>
Example 2
strcmp() function returns a negative value (< 0)
when the string passed as the first parameter is smaller than the second parameter, see example:
<?php
$str1 = 'a';
$str2 = 'b';
echo strcmp($str1,$str2); //prints -1 (which is < 0 )
?>
Example 3
If both strings are equal, strcmp() returns 0, see example:
<?php
$str1 = 'apache';
$str2 = 'apache';
echo strcmp($str1,$str2); //prints 0
?>