PHP strcmp() string function



PHP strcmp() function

The PHP strcmp() string function used to compare two strings. If both string are same then returns zero(0), if does not same returns any other digit value except zero(0) depend on length of both string.

The PHP strcmp() function syntax

strcmp(“string1”, “string2”);

Here, we have two strings string1 and string2 if both are same then return zero(0).

The strcmp() function works like :

returns 0 if both strings are equal

returns >0 if string1 is greater than string2

returns <0 if string2 is greater than string1

PHP strcmp() string function example

<?php
echo "The sting compare =". strcmp("Meera", "Meera");
?>

The out put is:
The string compare =  0, as both strings are equal.

 

<?php
echo "The sting compare = ". strcmp("Meera","meera");
?>

The string compare = -1 , here both string are same but there is a different in letter case so  the result is -1.

 

<?php
echo "The sting compare = ". strcmp("meera academy","meera");
?>

The string compare = 8, because the string1 is greater than string2.

strcmp() function php form example

Now lets take an example of php form for understand strcmp() string function. create a php web form with two textboxes for input two values and a submit button control for compare entered two strings are same or not using strcmp() function.

<html>
<head>
<title>PHP strcmp() Function</title>
</head>
<body>

<FORM method="POST" action="firstexample.php">

String1 : <input type="text" name="str1"> <br/>
String2 : <input type="text" name="str2"> <br/>
<br/>
<input type="submit" name="Submit1" value="compare string()">

</FORM>

<?php
if(isset($_POST['Submit1']))
{ 
if(strcmp($_POST["str1"],$_POST["str2"]))
{
echo "strings are not same";
}
else
{
echo "strings are same";
}
}
?>

</body>
</html>

The output of above php strcmp() function is:

PHP strcmp() string function example
PHP strcmp() string function example

Leave a Reply

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