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:

Explanation of strcasecmp() function definition
Function PartDescription
intType of value this function returns, which is an integer (int)
strcasecmpThe function name
stringFirst parameter type, this function accepts only string data type
$str1First parameter names, variables that hold the data
stringSecond parameter type, this function accepts only string data type
$str2Second 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

?>

Contents and Related Tutorials

  1. A list of PHP Comparison Operators with examples
  2. Assignment = vs Equal == vs Identical === Operators
  3. Basics of Strings Comparing
  4. Case Sensitive: Compare strings with strcmp() function
  5. Case Insensitive strings comparison with strcasecmp() function