Using PHP's natsort() Function for Natural Order Array Sorting

This article explains PHP's natsort() function, which performs natural order sorting on arrays while preserving key/value associations, describes its parameters and return values, and provides a complete example comparing standard sorting with natural sorting to illustrate the differences in output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP's natsort() Function for Natural Order Array Sorting

The natsort() function in PHP sorts an array using a natural order algorithm that mimics the way humans sort alphanumeric strings, while keeping the original keys associated with their values.

Parameters : It accepts a single argument passed by reference – the array to be sorted.

Return value : The function returns TRUE on success and FALSE on failure.

Example :

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

// Standard sorting
asort($array1);
echo "Standard sorting
";
print_r($array1);

// Natural order sorting
natsort($array2);
echo "
Natural order sorting
";
print_r($array2);
?>

Output :

Standard sorting
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

The example demonstrates that standard sorting orders the strings lexicographically ("img1", "img10", "img12", "img2"), whereas natural sorting orders them as a human would expect ("img1", "img2", "img10", "img12").

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPArraySortingphp-functionsnatsortnatural sorting
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.