The strnatcmp Function

The strnatcmp function performs a comparison of two strings using natural order sorting. Unlike standard comparison, this function recognizes numbers within strings and compares them by their numerical value. The function returns 0 if the strings are identical, a number less than 0 if the first string is less than the second, and a number greater than 0 if the first string is greater than the second.

Syntax

phpstrnatcmp(string $str1, string $str2): int

Example

Comparing strings with numbers using standard comparison and with strnatcmp:

php<?php
  $res1 = strcmp("file2.txt", "file10.txt");
  $res2 = strnatcmp("file2.txt", "file10.txt");
  
  echo "strcmp result: " . $res1 . "\n";
  echo "strnatcmp result: " . $res2;
?>

Code execution result:

phpstrcmp result: 1
strnatcmp result: -1

Example

Comparing strings with different numbers:

php<?php
  $res = strnatcmp("image5.jpg", "image15.jpg");
  echo $res;
?>

Code execution result:

php-1

Example

Comparing identical strings:

php<?php
  $res = strnatcmp("hello123", "hello123");
  echo $res;
?>

Code execution result:

php0

See Also

  • the strcmp function,
    which performs a binary-safe string comparison
  • the strcasecmp function,
    which compares strings case-insensitively
  • the natcasesort function,
    which sorts an array using natural order without case sensitivity