Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP strnatcmp() function

Reference for PHP strnatcmp(): natural-order string comparison that treats digit runs as numbers, strnatcasecmp(), natsort() and file-name sorting.

strnatcmp() compares two strings using "natural order", the way a person would sort file names. Runs of digits are compared as numbers, so "img2" comes before "img10", whereas strcmp() puts "img10" first because 1 is less than 2.

It is case-sensitive; strnatcasecmp() is the case-insensitive twin. Both return a negative number, 0 or a positive number.

PHP
<?php
echo strnatcmp("img2", "img10");  // -1
echo strcmp("img2", "img10");     // 1

Try it

PHP Natural versus ordinary comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Sorting file names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
strnatcmp(string $string1, string $string2): int
strnatcasecmp(string $string1, string $string2): int
Name Description
$string1 The first string.
$string2 The second string.

Return value: -1, 0 or 1.

Usage notes

  • Digit runs are numbers. "x9" is less than "x10". Leading zeros are handled specially, so "01" and "1" are not always equal.
  • Not full version comparison. For version numbers such as "1.0.0-beta", use version_compare().
  • Sorting arrays: natsort() and natcasesort() sort an array in natural order and preserve keys. sort($a, SORT_NATURAL) and SORT_NATURAL | SORT_FLAG_CASE reindex it.
  • ASCII only, bytes only. It does not know locale-specific collation or Unicode digits.
  • Do not use the result as a boolean; 0 means equal.
  • Decimals are not recognized: "1.5" and "1.10" are compared as the number 1, a dot, then 5 and 10 separately.