PHP strcmp() Function
Topic: PHP String ReferencePrev|Next
Description
The strcmp()
function compares two strings.
This function is case-sensitive. For case-insensitive searches, use the strcasecmp()
function.
The following table summarizes the technical details of this function.
Return Value: | Returns a negative value (< 0 ) if string1 is less than string2; a positive value (> 0 ) if string1 is greater than string2, and 0 if both strings are equal. |
---|---|
Version: | PHP 4+ |
Syntax
The basic syntax of the strcmp()
function is given with:
The following example shows the strcmp()
function in action.
Example
Run this code »<?php
// Sample strings
$str1 = "Hello";
$str2 = "HELLO";
// Test if both strings are equal
if(strcmp($str1, $str2) !== 0) {
echo "The two strings are not equal in a case-sensitive comparison.";
}
?>
Parameters
The strcmp()
function accepts the following parameters.
Parameter | Description |
---|---|
string1 | Required. Specifies the first string to compare. |
string2 | Required. Specifies the second string to compare. |
More Examples
Here're some more examples showing how strcmp()
function actually works:
The following example compares two strings where the first string is less than the second.
Example
Run this code »<?php
// Sample strings
$str1 = "Hello";
$str2 = "Hello John!";
// Comparing the two strings
echo strcmp($str1, $str2);
?>
The following example compares two strings where the first string is greater than the second.
Example
Run this code »<?php
// Sample strings
$str1 = "Hello Peter!";
$str2 = "Hello";
// Comparing the two strings
echo strcmp($str1, $str2);
?>