Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.
Hello Friends Today, through this tutorial, I will tell you How to Use `strcmp()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP, the `strcmp()` function is used to compare two strings. It returns 0 if the two strings are equal, a negative value if the first string is less than the second one, and a positive value if the first string is greater than the second one, based on their ASCII values.
As of PHP 8.1 and 8.2, the `strcmp()` function remains the same. Here’s an example demonstrating its usage:
<?php // Example 1: Basic usage of strcmp() $str1 = "apple"; $str2 = "banana"; $result = strcmp($str1, $str2); if ($result == 0) { echo "The strings are equal."; } elseif ($result < 0) { echo "The first string is less than the second one."; } else { echo "The first string is greater than the second one."; } echo "\n"; // Example 2: Case-insensitive comparison $str3 = "Apple"; $str4 = "apple"; $result = strcmp($str3, $str4); if ($result == 0) { echo "The strings are equal."; } else { echo "The strings are not equal."; } echo "\n"; ?>
Output:
The first string is less than the second one. The strings are not equal.
In Example 1, the `strcmp()` function compares “apple” and “banana”, and since “apple” comes before “banana” alphabetically, it returns a negative value.
In Example 2, we compare “Apple” and “apple”. Since the comparison is case-sensitive, the function returns a non-zero value indicating that the strings are not equal.