Strcmp and Strcasecmp Function in PHP

Introduction

I am describing two string functions in PHP; the functions are "strcmp()" which is case sensitive and "strcasecmp()" which is case insensitive. I first discuss the strcmp function with syntax and an example. The strcmp() function is a string function to compare two strings passed as parameters.

Syntax

strcmp($string1, $string2);

 

strcmp() returns:

  • < 0 if string1 is less than string2.

  • > 0 if string1 is greater than string2.

  • 0 if str1 and str2 are equal.

Example1

 

The strcmp() function returns a positive value when the first parameter is greater than the second parameter, so the output is a positive value. Such as:

 

<?php

$string1 = 'MCN';

$string2 = 'ABC';

$result = strcmp($string1,$string2);

echo "Print the result <b>$result</b>";

?>

Output

strcmp in php1.jpg

Example2

The Strcmp() function returns a negative value, when the first parameter is less than the second parameter, so the output is a negative value. Such as:

<?php

$string1 = 'ABC';

$string2 = 'MCN';

$result = strcmp($string1,$string2);

echo "Print the result <b>$result</b>";

?>

Output

strcmp in php2.jpg

Example3

When both parameters are equal or both strings are the same then the output is Zero.

<?php

$string1 = 'MCN Solution';

$string2 = 'MCN Solution';

$result = strcmp($string1,$string2);

echo "Print the result <b>$result</b>";

?>

Output

strcmp in php3.jpg

strcasecmp()

I am describing the strcasecmp() function next. The "strcasecmp()" function is a case insensitive string comparison function. This function compares two strings; the strcmp() function is case sensitive but the strcmp() and strcasecmp() functions both work the same. But it does not distinguish between uppercase and lowercase letters. 

Syntax

strcasecmp($string1, $string2);

 

Example

<?php

$string1 = 'MCN SOLUTION PVT.LTD.';

$string2 = 'mcn solution pvt.ltd.';

$result = strcasecmp($string1,$string2);

echo "Print the result <b>$result</b>";

?>

 

Output

 strcasecmp function in-php.jpg

 


Similar Articles