Comparing Strings with strcmp() function

PHP strcmp() function: PHP offer a bit more than just comparing strings and returning true or false. The strcmp() function compares two strings and this comparison is case sensitive.

strcmp() prototype

int strcmp ( string $str1 , string $str2 )

This means that strcmp() function accepts two string (comma separated) as input to compare and returns an int (integer). See the following table to understand the above function definition in an easy way:

Explanation of strcmp() function definition
Function PartDescription
intType of value this function returns, which is an integer (int)
strcmpThe function name
stringFirst parameter type, this function accepts only string data type
$str1First parameter names, variables that hold the data
stringSecond parameter type, this function accepts only string data type
$str2Second parameter name, variables that hold the data

Syntax

strcmp($str1, $str2)

Return values

The strcmp() function returns:

  • < 0 if $str1 is less than $str2
  • > 0 if $str1 is greater than $str2
  • 0 if $str1 and $str2 are equal

Examples

Example 1

strcmp() function returns a positive value (> 0) when the string passed as the first parameter is greater than the second parameter, see example:

<?php

    $str1 = 'b';
    $str2 = 'a';
    echo strcmp($str1,$str2); //prints 1 (which is > 0)

?>

Example 2

strcmp() function returns a negative value (< 0) when the string passed as the first parameter is smaller than the second parameter, see example:

<?php

    $str1 = 'a';
    $str2 = 'b';
    echo strcmp($str1,$str2); //prints -1 (which is < 0 )

?>

Example 3

If both strings are equal, strcmp() returns 0, see example:

<?php 

    $str1 = 'apache';
    $str2 = 'apache';
    echo strcmp($str1,$str2); //prints 0

?>

Contents and Related Tutorials

  1. A list of PHP Comparison Operators with examples
  2. Assignment = vs Equal == vs Identical === Operators
  3. Basics of Strings Comparing
  4. Case Sensitive: Compare strings with strcmp() function
  5. Case Insensitive strings comparison with strcasecmp() function