strcmp() function is used to compare two strings in php. This function is case-sensitive and binary-safe. If we need case-insensitive comparison, we can use the strcasecmp() function.

Syntax

strcmp(string1,string2)

string1 – This parameter is required. It refers the first string to compare.

string2 – This parameter is required. It refers the second string to compare.

This function takes two strings str1 and str2 as parameters. The strcmp() function returns:

  • Returns 0 – If two strings are equal.
  • Returns a negative value (<0) – If the str1 is lesser than str2.
  • Returns a positive value(>0) – If the str1 is greater than str2.

Example

<?php
$str1 = "PHP";
$str2 = "PHP";
$str3 = "PHP Tuts";
$str4 = "PHP Tutorials";
echo strcmp($str1, $str2); // Output: 0
echo '<br>';
echo strcmp($str1,$str3); // Output: -5
echo '<br>';
echo strcmp($str3,$str4); // Output: 1
echo '<br>';
?>

Categorized in: