Home > Mobile >  Sort array in custom order using PHP
Sort array in custom order using PHP

Time:02-25

I want to sort the array in the below order:

$sorted_array = ["diamond", "platinum", "gold", "silver", "bronze", "standard", "branding"];

The original array may come in different order like below:

$data = ["platinum", "gold", "silver", "bronze", "standard", "branding", "diamond"];

But I wanted always like the above $sorted_array values. If any values are not present in $data then it will take the position of of other. For example: if diamond is not in the array then first position will take platinum.

CodePudding user response:

I would use the array containing all values in the correct order, and then filter out the elements which are not in the $data array:

$sortOrder = [ 'diamond', 'platinum', 'gold', 'silver', 'bronze', 'standard', 'branding' ];

$data = [ 'platinum', 'gold', 'silver', 'bronze', 'standard', 'branding', 'diamond' ];
$result = array_filter($sortOrder, fn($value) => in_array($value, $data));
  • Related