PHP String Compare Case Insensitive

PHP String Compare Case Insensitive

How to compare case insensitive two strings in PHP. This tutorial would love to share with how to compare two case insensitive string in PHP.

PHP string compare case insensitive

You can use the PHP strcasecmp() function for compare two strings ( case insensitive ). This function is similar to strncasecmp(), the only difference is that the strncasecmp() provides the provision to specify the number of characters to be used from each string for the comparison.

Syntax

strcasecmp(str1,str2)

Parameters strcasecmp() function

ParameterDescription
str1Required. The first string to compare
str2Required. The second string to compare

Note:- This function returns an integer value, see the list of condition values

  • The function returns 0 – if the two strings are equal.
  • returns < 0 – if str1 is less than str2
  • returns > 0 – if str1 is greater than str2

Example First – Compare two strings in PHP (Case Sensitive)

<?php 
// PHP program to demonstrate how to compare two strings (case sensitive)
  
$str1 = "I love PHP"; 
$str2 = "I LOVE PHP"; 
   
// compare strings in PHP with strcasecmp 
$str=strcasecmp($str1, $str2);  
   
echo "$str";  

?>
Source Code – Compare Two String In PHP
<!DOCTYPE html>
<html lang="en">
<head>
    <title>compare strings in PHP with strcasecmp</title>
</head>
<body>
<h4>compare strings in PHP with strcasecmp() function</h4>

<?php 
	// PHP program to demonstrate how to compare two strings (case sensitive)
	$str1 = "I love PHP"; 
	$str2 = "I LOVE PHP"; 
	   
	// compare strings in PHP with strcasecmp 
	$str=strcasecmp($str1, $str2);  
	   
	echo "$str";  
?>

</body>
</html>                                		

Example Second – Compare two string In PHP

<?php 
// PHP program to demonstrate how to compare two strings (case sensitive)
  
$str1 = "I love PHP"; 
$str2 = "I Love"; 
   
// compare strings in PHP with strcasecmp 
$str=strcasecmp($str1, $str2);  
   
echo "$str";  

?>
Source Code – Compare Two String In PHP
<!DOCTYPE html>
<html lang="en">
<head>
    <title>compare strings in PHP with strcasecmp</title>
</head>
<body>
<h4>compare strings in PHP with strcasecmp</h4>

<?php 
// PHP program to demonstrate how to compare two strings (case sensitive)
  
$str1 = "I love PHP"; 
$str2 = "I Love"; 
   
// str1 < str2 , The strings are not equal 
$str=strcasecmp($str1, $str2);  
   
echo "$str";  

?>

</body>
</html>                                		

Conclusion

PHP compares two string (case insensitive). Here you have learned how to use PHP strcasecmp() for compare two strings(case insensitive).

Leave a Reply

Your email address will not be published. Required fields are marked *