I need to sort an array by clothes size like in the exemple below.
I need to start from :['M', 'M', 'S', 'XL', 'L', 'XL', 'S', 'M', 'XL', 'S']
and arrive to : ['S', 'S', 'S', 'M', 'M', 'M', 'L', 'XL', 'XL', 'XL']
Here you are what i did. It works but I dont like it , it doesnt seems optimize. I wish i have only one foreach
function trier(array $table):array{
$tableauVide=[];
foreach($table as $element){
if($element=='S'){
array_push($tableauVide,$element);
}
}
foreach($table as $element){
if($element=='M'){
array_push($tableauVide,$element);
}
}
foreach($table as $element){
if($element=='L'){
array_push($tableauVide,$element);
}
}
foreach($table as $element){
if($element=='XL'){
array_push($tableauVide,$element);
}
}
return $tableauVide; }
var_dump(trier(['M', 'M', 'S', 'XL', 'L', 'XL', 'S', 'M', 'XL', 'S']));
I'm new to PHP , so i have read a lot of stuff to sort an array. Like the function usort( it seems thats the way to sort an array to a specific way but i can't figure out how it works. may you give me a hint with it ? or how would you process to make it better ?
Thanks