php sort array by value without changing keys code example

Example 1: php sort array by specific key

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

Example 2: 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 3: php order array by specific key

function cmp($a, $b)
    {
        return strcmp($a->display_name, $b->display_name);
    }

    usort($blogusers, "cmp");

    foreach ($blogusers as $bloguser)
    {
        ...

Tags:

Php Example