PHP strnatcmp() Function
In this chapter you will learn:
- Definition for PHP strnatcmp() Function
- Syntax for PHP strnatcmp() Function
- Parameter for PHP strnatcmp() Function
- Return for PHP strnatcmp() Function
- Example - Compare two strings using a "natural" algorithm (case-sensitive)
- Example - Difference between natural algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp)
Definition
The strnatcmp() function compares two strings in a natural way.
In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in "10" is less than 2.
Syntax
PHP strnatcmp() Function has the following syntax.
strnatcmp(string1,string2)
Parameter
Parameter | Is Required | Description |
---|---|---|
string1 | Required. | First string to compare |
string2 | Required. | Second string to compare |
Return
This function returns:
- 0 - if the two strings are equal
- <0 - if string1 is less than string2
- >0 - if string1 is greater than string2
Example 1
Compare two strings using a "natural" algorithm (case-sensitive):
<?php// j a va 2s .c o m
echo strnatcmp("2Hello world!","10Hello world!");
echo "\n";
echo strnatcmp("10Hello world!","2Hello world!");
?>
The code above generates the following result.
Example 2
Difference between natural algorithm (strnatcmp) and regular computer string sorting algorithms (strcmp):
<?php/*from ja v a 2 s. c om*/
$arr1 = $arr2 = array("PHP1","PHP2","PHP10","PHP01","PHP100","PHP20","PHP30","PHP200");
echo "Standard string comparison"."\n";
usort($arr1,"strcmp");
print_r($arr1);
echo "\n";
echo "Natural order string comparison"."\n";
usort($arr2,"strnatcmp");
print_r($arr2);
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP strncasecmp() Function
- Syntax for PHP strncasecmp() Function
- Parameter for PHP strncasecmp() Function
- Return for PHP strncasecmp() Function
- Example - Compare two strings (case-insensitive)
- Example - Compare two strings (case-insensitive = Hello and hELLo will output the same)
Home » PHP Tutorial » PHP String Functions