Wasinha Wasinha - 1 month ago 10
PHP Question

Array sorting doesn't work the way it should be

I'm trying to sort an array,but it doesn't work the way I want to.

My code is as follows.

<?php
$classroom = array("4/10","4/2","4/1","4/11","5/2","1/2","5/1","5/10","5/12");
sort($classroom);
print_r($classroom);
?>


The result is:

Array ( [0] => 1/2 [1] => 4/1 [2] => 4/10 [3] => 4/11 [4] => 4/2 [5] => 5/1 [6] => 5/10 [7] => 5/12 [8] => 5/2 )


I would like to sort it to be:

1/2,4/1,4/2,4/10,4/11,5/1,5/2,5/10,5/12


I'm quite new to sort functions. Would you please give me an example of using usort?

Answer

Coincidentally natsort seems to work:

<?php

$classroom = array("4/10","4/2","4/1","4/11","5/2","1/2","5/1","5/10","5/12");

natsort($classroom);
print_r($classroom);

Prints:

Array
(
    [0] => 1/2
    [1] => 4/1
    [4] => 4/2
    [2] => 4/10
    [3] => 4/11
    [5] => 5/1
    [8] => 5/2
    [6] => 5/10
    [7] => 5/12
) 

Full disclosure: I'm not 100% sure it would work for all use cases, I haven't tested it. Use with caution.