strnatcmp() Function Use in PHP 8.4 and PHP 8.5

strnatcmp() behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes to this function in either release. Its most recent documented behavioral change occurred in PHP 8.2.0.

Function

strnatcmp() compares two strings using a "natural order" algorithm, which orders alphanumeric strings the way a human would (e.g., "img2" comes before "img10"). Note that this comparison is case-sensitive.

Signature:

strnatcmp(string $string1, string $string2): int

Return Values:

  • < 0 if $string1 is less than $string2
  • > 0 if $string1 is greater than $string2
  • 0 if they are equal

The exact integer value (e.g., -1, 1, or the length difference) should not be relied upon; only the sign matters.

Example

The classic use case is sorting an array of filenames where standard string comparison would produce an unintuitive order.

<?php
$files = ["img12.png", "img10.png", "img2.png", "img1.png"];

// Standard computer sorting (strcmp)
$standard = $files;
usort($standard, "strcmp");
print_r($standard);
/* Output:
Array (
   [0] => img1.png
   [1] => img10.png
   [2] => img12.png
   [3] => img2.png   // "img2" comes last because "1" < "2"
)
*/

// Natural order sorting (strnatcmp)
$natural = $files;
usort($natural, "strnatcmp");
print_r($natural);
/* Output:
Array (
   [0] => img1.png
   [1] => img2.png   // "img2" is correctly placed before "img10"
   [2] => img10.png
   [3] => img12.png
)
*/
?>

8 Views