Comparing Strings with strcasecmp()
function
PHP strcasecmp()
function: This function works same as strcmp()
which is case sensitive.
If no case sensitivity is required, then you can use strcasecmp()
function. It works as strcmp()
but it does not distinguish between uppercase and lowercase letters.
strcasecmp() prototype
int strcasecmp ( string $str1 , string $str2 )
This means that strcasecmp()
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) |
strcasecmp | 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
strcasecmp($str1, $str2)
Return values
The strcasecmp()
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
strcasecmp()
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 strcasecmp($str1,$str2); //prints 1 (which is > 0)
?>
Example 2
strcasecmp() 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 strcasecmp($str1,$str2); //prints -1 (which is < 0 )
?>
Example 3
If both strings are equal, strcasecmp() returns 0, see example:
<?php
$str1 = 'apache';
$str2 = 'apache';
echo strcasecmp($str1,$str2); //prints 0
?>
Example 4
strcasecmp() is case insensitive function and it does not distinguish between uppercase and lowercase letters, it'll return 0 even if letters case do not match, see example:
<?php
$str1 = 'ApAchE';
$str2 = 'apache';
echo strcasecmp($str1,$str2); //prints 0
?>