Q:

PHP: Sort an array of bytes

Looking for a possible way to sort this following array. taking the bytes as sting in consideration. 
Array
(
    [0] => 100 MB
    [4] => 10 MB
    [8] => 1GB
    [12] => 20 MB
    [16] => 250 MB
    [20] => 2GB
    [24] => 4 MB
    [28] => 500 MB
    [32] => 50 MB
    [36] => 5GB
    [40] => 8GB
    [44] => 0 MB
)

A:

You can sort this array using custom comparison function by converting the string to the value of byte.
$arr = array(
    0 => "100 MB",
    4 => "10 MB",
    8 => "1GB",
    12 => "20 MB",
    16 => "250 MB",
    20 => "2GB",
    24 => "4 MB",
    28 => "500 MB",
    32 => "50 MB",
    36 => "5GB",
    40 => "8GB",
    44 => "0 MB"
);

function toByte($value) {
    $multiple  = (stripos($value, "K") > 0) ? 1024 : 1;
    $multiple *= (stripos($value, "M") > 0) ? 1048576 : 1;
    $multiple *= (stripos($value, "G") > 0) ? 1073741824 : 1;

    return floatval($value) * $multiple;
}

usort($arr, function($v1, $v2) {
    return toByte($v1) - toByte($v2);
});

var_dump($arr);

