How to compare two strings in PHP?

Member

by darion , in category: PHP General , 2 years ago

How to compare two strings in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 2 years ago

@darion 

In PHP, you can compare two strings using various string comparison functions like strcmp, strcasecmp, substr_compare, strnatcmp, etc. Here are some examples:

  1. Using strcmp function:


The strcmp function compares two strings byte by byte and returns 0 if they are equal, -1 if the first string is less than the second one, and 1 if the first string is greater than the second one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$str1 = "hello";
$str2 = "world";
$result = strcmp($str1, $str2);

if ($result == 0) {
    echo "The two strings are equal";
} else if ($result < 0) {
    echo "The first string is less than the second one";
} else {
    echo "The first string is greater than the second one";
}


  1. Using strcasecmp function:


The strcasecmp function compares two strings case-insensitively and returns 0 if they are equal, -1 if the first string is less than the second one, and 1 if the first string is greater than the second one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$str1 = "hello";
$str2 = "HELLO";
$result = strcasecmp($str1, $str2);

if ($result == 0) {
    echo "The two strings are equal";
} else if ($result < 0) {
    echo "The first string is less than the second one";
} else {
    echo "The first string is greater than the second one";
}


  1. Using substr_compare function:


The substr_compare function compares two substrings within a string and returns 0 if they are equal, -1 if the first substring is less than the second one, and 1 if the first substring is greater than the second one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$str1 = "hello world";
$str2 = "world";
$result = substr_compare($str1, $str2, 6);

if ($result == 0) {
    echo "The two substrings are equal";
} else if ($result < 0) {
    echo "The first substring is less than the second one";
} else {
    echo "The first substring is greater than the second one";
}


  1. Using strnatcmp function:


The strnatcmp function compares two strings using a natural order algorithm and returns 0 if they are equal, -1 if the first string is less than the second one, and 1 if the first string is greater than the second one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$str1 = "file10.txt";
$str2 = "file2.txt";
$result = strnatcmp($str1, $str2);

if ($result == 0) {
    echo "The two strings are equal";
} else if ($result < 0) {
    echo "The first string is less than the second one";
} else {
    echo "The first string is greater than the second one";
}