Search code examples
phparrayssortingkeyversion

array sort by keys.


I have a following array,

$versions = array
(
    '0.9.md5' => '/var/www/md5_test/0.9.md5',
    '1.0.0.md5' => '/var/www/md5_test/1.0.0.md5',
    '1.0.1.md5' => '/var/www/md5_test/1.0.1.md5',
    '1.0.2.md5' => '/var/www/md5_test/1.0.2.md5',
    '1.0.3.md5' => '/var/www/md5_test/1.0.3.md5',
    '1.0.9.1.md5' => '/var/www/md5_test/1.0.9.1.md5',
    '1.0.9.10.1.md5' => '/var/www/md5_test/1.0.9.10.1.md5',
    '1.0.9.10.md5' => '/var/www/md5_test/1.0.9.10.md5',
    '1.1.3.md5' => '/var/www/md5_test/1.1.3.md5',
    '1.0.9.2.md5' => '/var/www/md5_test/1.0.9.2.md5',
    '1.0.9.3.md5' => '/var/www/md5_test/1.0.9.3.md5',
    '1.0.9.8.md5' => '/var/www/md5_test/1.0.9.8.md5',
    '1.0.9.9.1.md5' => '/var/www/md5_test/1.0.9.9.1.md5',
    '1.0.9.9.md5' => '/var/www/md5_test/1.0.9.9.md5',
    '1.0.9.md5' => '/var/www/md5_test/1.0.9.md5',
    '1.1.0.md5' => '/var/www/md5_test/1.1.0.md5',
    '1.1.1.md5' => '/var/www/md5_test/1.1.1.md5',
    '1.1.2.md5' => '/var/www/md5_test/1.1.2.md5',
);

In this array i want to sort this by keys. I have searched,

Ex: It should order like: 1.0.9.md5, 1.0.9.1.md5,.. , 1.0.9.10.md5, 1.0.9.10.1.md5

I have tried

ksort($versions);

But i could't get exactly what i want.


Solution

  • If these are version numbers, and you need to sort by the version so that 1.0.9.2.md5 comes before 1.0.9.10.1.md5 then you need a custom sort based on semantic versioning:

    uksort($versions, 'version_compare');
    

    Demo