php sort array maintain keys code example

Example 1: php sort array by key

$weight = [
    'Pete' => 75, 
    'Benjamin' => 89,
    'Jonathan' => 101
  ];  	
  ksort($weight);

Example 2: php sort array by value and keep key

$weight = [
    'Pete' => 75,
    'Benjamin' => 309,
    'Jonathan' => 101
];
asort($weight);
/*
weight is now:
Array
(
    [Pete] => 75
    [Jonathan] => 101
    [Benjamin] => 309
)
To sort descending instead use: arsort
*/

Example 3: php sort array by specific key

usort($array, function ($a, $b) {
  return ($a['specific_key'] < $b['specific_key']) ? -1 : 1;
});

Example 4: php sort array of array by key

$inventory = [
	['price' => 10.99, 'product' => 'foo 1'],
    ['price' => 5.99, 'product' => 'foo 2'],
  	['price' => 100, 'product' => 'foo 3'],
  
];

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);

Example 5: php rsort retain keys

//Sort an array in reverse order and maintain index association
arsort($myArray)

Example 6: php array sort by key value

To PHP sort array by key, you should use: 
	ksort() (for ascending order) or krsort() (for descending order). 
      
To PHP sort array by value, you will need functions:
	asort() and arsort() (for ascending and descending orders).

Tags:

Php Example