Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to compare two text strings in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 133
    Comment on it

    There are different methods to check two text strings are equal or not in PHP. This article defines the methods which can be used for comparing two text strings.


    1. '==' : == operator is most commonly used operator for comparing two strings. If the text of both strings are same, it returns TRUE, otherwise returns FALSE.


    Example :
    $str1 = "Hello Friends";
    $str2 = "Hello Friends";
    if($str1 == $str2){
     echo "Matched";
    }else{
     echo "Not Matched";
    }
    

    Output : Matched


    2. strcmp() : strcmp() is a built-in function in PHP, which is used to compare two strings. strcmp() function is used to perform binary safe string comparison. It returns the integer value as a result which defines the following cases :


    • 0 : If both strings are equal
    • >0 : If first string is bigger than second string
    • <0 : If first string is smaller than second string

    Example 1:

    $str1 = "Hello Friends";
    $str2 = "Hello Friends";
    echo strcmp($str1, $str2);
    

    Output : 0


    Example 2:

    $str1 = "Hello Friends";
    $str2 = "Hello";
    echo strcmp($str1, $str2);
    

    Output : 8


    The above two methods compare strings in case-sensitive manner, PHP also provides strcasecmp() function to compare strings in case-insensitive manner. strcasecmp() returns the same results like strcmp().


    Example : a. Case-sensitive comparison

    $str1 = "Hello Friends";
    $str2 = "hello Friends";
    echo strcmp($str1, $str2);
    

    Output : -32


    b. Case-insensitive comparison

    $str1 = "Hello Friends";
    $str2 = "hello friends";
    echo strcasecmp($str1, $str2);
    

    Output : 0


 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: