php sort associative array code example

Example 1: sort array of array php

sort() //sort arrays in ascending order
rsort() //sort arrays in descending order
asort() //sort associative arrays in ascending order, according to the value
ksort() //sort associative arrays in ascending order, according to the key
arsort() //sort associative arrays in descending order, according to the value
krsort() //sort associative arrays in descending order, according to the key
  
//Example
  $array = array(1, 3, 2);
  sort($array) //1, 2, 3

Example 2: php sort by associative array value

//php 7+
usort($inventory, function ($item1, $item2) {
    return $item1['price'] <=> $item2['price'];
});

Example 3: 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 4: 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