String comparison functions help you check if two pieces of text are the same or which one comes first in order. This is useful when sorting or checking user input.
0
0
String comparison functions in PHP
Introduction
Checking if a username entered matches a stored username.
Sorting a list of words alphabetically.
Comparing passwords or codes for equality.
Finding if one string appears before another in dictionary order.
Validating form inputs against expected values.
Syntax
PHP
strcmp(string $str1, string $str2): int strcasecmp(string $str1, string $str2): int strncmp(string $str1, string $str2, int $length): int strncasecmp(string $str1, string $str2, int $length): int
These functions return 0 if the strings are equal.
A negative number means the first string is less than the second; a positive means it is greater.
Examples
Compare two strings exactly, case-sensitive.
PHP
$result = strcmp("apple", "banana"); // $result will be negative because "apple" comes before "banana"
Compare two strings ignoring uppercase or lowercase differences.
PHP
$result = strcasecmp("Apple", "apple"); // $result will be 0 because comparison ignores case
Compare only the first few characters of two strings.
PHP
$result = strncmp("applepie", "applesauce", 5); // Compares only first 5 characters
Compare first few characters ignoring case.
PHP
$result = strncasecmp("ApplePie", "appleSauce", 5); // Case-insensitive comparison of first 5 characters
Sample Program
This program compares strings using different functions and prints what it finds. It shows case-sensitive and case-insensitive comparisons, and compares full strings or just the first few characters.
PHP
<?php // Compare two strings case-sensitive $result1 = strcmp("hello", "Hello"); // Compare two strings ignoring case $result2 = strcasecmp("hello", "Hello"); // Compare first 3 characters case-sensitive $result3 = strncmp("hello", "helium", 3); // Compare first 3 characters ignoring case $result4 = strncasecmp("Hello", "heLium", 3); // Print results if ($result1 === 0) { echo "strcmp: Strings are equal\n"; } elseif ($result1 < 0) { echo "strcmp: 'hello' is less than 'Hello'\n"; } else { echo "strcmp: 'hello' is greater than 'Hello'\n"; } if ($result2 === 0) { echo "strcasecmp: Strings are equal ignoring case\n"; } if ($result3 === 0) { echo "strncmp: First 3 characters are equal\n"; } else { echo "strncmp: First 3 characters are different\n"; } if ($result4 === 0) { echo "strncasecmp: First 3 characters are equal ignoring case\n"; } else { echo "strncasecmp: First 3 characters are different ignoring case\n"; }
OutputSuccess
Important Notes
Remember that strcmp and strncmp are case-sensitive.
Use strcasecmp and strncasecmp when you want to ignore letter case.
These functions return an integer, not a boolean true/false.
Summary
String comparison functions check if texts are equal or which comes first.
Use strcmp and strncmp for case-sensitive checks.
Use strcasecmp and strncasecmp to ignore case differences.