3v4l.org

run code in 300+ PHP versions simultaneously
<?php const UNIT_FACTOR = [ 'g' => 1, 'Kg' => 1000, ]; $weights = ['1 Kg','300 g','1.5 Kg','20 g','5 Kg']; $grams = []; foreach ($weights as $weight) { sscanf($weight, '%f%s', $amount, $unit); $grams[] = $amount * UNIT_FACTOR[$unit]; } array_multisort($grams, $weights); var_export($weights);
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
array ( 0 => '20 g', 1 => '300 g', 2 => '1 Kg', 3 => '1.5 Kg', 4 => '5 Kg', )

preferences:
122.46 ms | 407 KiB | 5 Q