3v4l.org

run code in 300+ PHP versions simultaneously
<?php $test = ['Red orange 2016','orange 2017' ,'Mango 2018' ,'Granny Smith apple 2018' ,'apple 2015']; $a = array(); // create two new arrays to hold fruit and year $b = array(); $temp = array(); foreach($test as $item){ $temp = explode(" ", $item); // explode the fruit/year to temp array $a[] = implode(" ", array_splice($temp, 0, -1)); // implode all but the last item as "fruit" $b[] = end($temp); // last item is the year } array_multisort($b, $a); // sort the new arrays $result=array(); for($i=count($b)-1; $i>=0; $i--){ // looping backwards to only count() once. (faster) $result[] = $a[$i] . " " . $b[$i]; // rebuild the new array with correct sorting. } var_dump($result);
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.6 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
array(5) { [0]=> string(10) "Mango 2018" [1]=> string(23) "Granny Smith apple 2018" [2]=> string(11) "orange 2017" [3]=> string(15) "Red orange 2016" [4]=> string(10) "apple 2015" }

preferences:
80.58 ms | 408 KiB | 5 Q