<?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);
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
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"
}