php

How to compare two strings in PHP

In this tutorial, we are going to see how to compare two strings in PHP. You can use strcmp() function in PHP to compare two strings. This function takes two string ‘str1’ and ‘str2’ as parameters. strcmp() function returns < 0 if ‘str1’ is less than ‘str2’; returns > 0 if ‘str1’ is greater than ‘str2’ and 0 if they are equal.
 

How to compare two strings in PHP
<?php
	$str1 = "Welcom to";
	$str2 = "Welcom to StackHowTo";
	echo strcmp($str1, $str2); 
?>

Output:

-12

 

 
strcmp() function compares two strings in case-sensitive. If you want a case insensitive comparison, you can use the strcasecmp() function, here is an Example.
 

How to compare two strings without case sensitive
<?php
	$str1 = "welcom to stackhowto";
	$str2 = "Welcom to StackHowTo";
	echo strcasecmp($str1, $str2); 
?>

Output:

0
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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