PHP natcasesort Function
last modified March 13, 2025
The PHP natcasesort
function sorts an array using a case-insensitive
"natural order" algorithm. It maintains index association and is useful for
sorting strings containing numbers.
Basic Definition
natcasesort
implements a natural order sorting algorithm while
ignoring case differences. It's similar to how humans would sort strings.
Syntax: natcasesort(array &$array): bool
. The function sorts the
array in place and returns true on success or false on failure.
Natural order sorting means numbers in strings are compared numerically rather than alphabetically. For example, "item2" comes before "item10".
Basic natcasesort Example
This demonstrates simple case-insensitive natural sorting of an array.
<?php $files = ["file1.txt", "File10.txt", "file2.txt", "FILE20.txt"]; natcasesort($files); print_r($files);
Output will be: Array ( [0] => file1.txt [2] => file2.txt [1] => File10.txt [3] => FILE20.txt ). The function ignores case and sorts numbers correctly.
Mixed Case Strings
Shows how natcasesort handles strings with varying case patterns.
<?php $items = ["Apple", "banana", "apricot", "Banana", "apple"]; natcasesort($items); print_r($items);
Case is ignored, placing all similar words together.
Natural Number Sorting
Demonstrates the natural order sorting of numbers within strings.
<?php $versions = ["version-2", "Version-10", "version-1", "VERSION-20"]; natcasesort($versions); print_r($versions);
Numbers are sorted numerically despite case differences.
Maintaining Key Association
Shows that natcasesort preserves the original key-value relationships.
<?php $data = [ "id3" => "Value C", "ID1" => "Value A", "id10" => "Value D", "Id2" => "Value B" ]; natcasesort($data); print_r($data);
Keys maintain their association with values after sorting.
Comparison with Other Sort Functions
Illustrates differences between natcasesort and regular sort functions.
<?php $items = ["img1.png", "Img10.png", "img2.png", "IMG12.png"]; $regular = $items; sort($regular); $natural = $items; natsort($natural); $naturalCase = $items; natcasesort($naturalCase); echo "Regular sort:\n"; print_r($regular); echo "\nNatural sort:\n"; print_r($natural); echo "\nNatural case-insensitive sort:\n"; print_r($naturalCase);
Regular sort orders alphabetically (1,10,12,2). Natural sorts respect numbers but are case-sensitive. Natcasesort combines both natural order and case insensitivity.
Best Practices
- Use when needed: Only for case-insensitive natural sorting.
- Performance: Slower than simple sorts due to complex comparison.
- Key preservation: Use when maintaining associations is important.
- Mixed data: Works best with strings containing numbers.
Source
This tutorial covered the PHP natcasesort
function with practical
examples showing its usage for natural case-insensitive array sorting.
Author
List all PHP Array Functions.