PHP strcmp() Function

PHP strcmp() function is used to compare two strings.” This function is case-sensitive and binary-safe(safe to use on binary data as well as regular text strings).

Syntax

strcmp($string1, $string2)

Parameters

  1. $string1 (required): The first string.
  2. $string2 (required): The second string.

Return Value

The function returns the random integer value depending on the condition of the match, which is given by:

    1. 0 if the strings are equal.
    2. negative if string1 is less than string2.
    3. positive if string1 is greater than string2.

    Visual RepresentationVisual Representation of PHP strcmp() Function

    Example 1: How to Use strcmp() function

    <?php
    
    $str1 = "AppDividend";
    $str2 = "AppDividend"; // Negative number, 'D' is less than 'd'
    $str3 = "Appdividend"; // Positive number, 'd' is greater than 'D'
    
    echo strcmp($str1, $str2)."\n";
    echo strcmp($str1, $str3)."\n";
    echo strcmp($str3, $str2)."\n";
    

    Output

    0
    -32
    32
    

    In the above example, first use case returns 0 because $str1 and $str2 are the same.

    But in the second and third use cases, Since ‘D’ (ASCII 68) is less than ‘d’ (ASCII 100), the difference is 32, hence the -32 and 32 in the output.

    Example 2: Passing two different strings

    <?php
    
    echo strcmp("Ronaldo", "Messi");
    

    Output

    1
    

    That’s it.

    Leave a Comment

    This site uses Akismet to reduce spam. Learn how your comment data is processed.