What is strcasecmp() function in PHP?

Overview

Strings can generally be of lowercase or uppercase characters, or both. It is also important to point out that these different cases have a particular value and do not interpret as the same character. For example, D and d are seen as different characters entirely using some comparison method techniques. But when the comparison is made between them using the strcasecmp() function, they will be considered the same.

The strcasecmp() function

The strcasecmp() function is one of the numerous methods from the rich PHP library. This method compares two strings and disregards the case type (uppercase or lowercase) of the characters that make up the strings. While comparing, the case of characters in strings will not be considered. This is called a case-insensitive comparison, where both case types are considered the same.

Syntax

strcasecmp($firstString,$secondString)

Parameters

  • $firstString: This is the first of the two strings that are to be compared.

  • $secondString: This is the second of the two strings that are to be compared.

Return value

On a successful comparison, this method returns a value that can be any of the three possible outcomes below:

  • A value less than (<) 0 if firstString is less than secondString.

  • A value greater than (>) 0 if firstString is greater than secondString.

  • A value 0 if firstString and secondString are equal.

Example

<?php
//defining variables
$firstSring1 = "you have a nice voice, honestly";
$secondSring1 = "you have a nice voice";
$firstSring2 = "This day is really marvellous";
$secondSring2 = "ThIS day is really marvellous, nice sky";
$firstSring3 = "THE SONG IS THE TOP rated today";
$secondSring3 = "the song is the TOP RATED TODAY";
//call the strcasecamp method
$output1 = strcasecmp($firstSring1,$secondSring1); //10
$output2 = strcasecmp($firstSring2,$secondSring2); //-10
$output3 = strcasecmp($firstSring3,$secondSring3); //0
//display the output from the method.
echo $output1 ."\n";
echo $output2 ."\n";
echo $output3;
?>

Explanation

  • Lines 3–11: We declare a pair of strings on which we’ll make a case-insensitive comparison.
  • Lines 14–16: We use the strcasecmp() function to compare some strings storing the output in an output variable.
  • Line 14: The first is greater than the second among the two compared strings.
  • Line 15: The first is less than the second among the two compared strings.
  • Line 16: The first and the second compared strings are equal.

Free Resources