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 `strnatcmp()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP 8.1 and 8.2, the `strnatcmp()` function remains unchanged from previous versions. This function is used to compare two strings in a natural order case-sensitive manner. Natural ordering means that numeric substrings are compared numerically, and non-numeric substrings are compared lexicographically.
Here’s the syntax of `strnatcmp()`:
<?php strnatcmp(string $str1, string $str2): int ?>
The function returns an integer less than 0 if `$str1` is less than `$str2`, an integer greater than 0 if `$str1` is greater than `$str2`, and 0 if they are equal.
Here’s an example of how to use `strnatcmp()`:
<?php $strings = ["img1.png", "img10.png", "img2.png", "img20.png"]; // Sort the array in natural order usort($strings, "strnatcmp"); // Output sorted array print_r($strings); ?>
Output:
Array
(
[0] => img1.png
[1] => img2.png
[2] => img10.png
[3] => img20.png
)
In this example, the array of strings is sorted in natural order using `usort()` along with `strnatcmp()` as the comparison function. This ensures that numbers within the strings are treated numerically rather than lexicographically, resulting in the correct ordering.