php sort array by 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 specific key
usort($array, function ($a, $b) {
return ($a['specific_key'] < $b['specific_key']) ? -1 : 1;
});
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: sort array by key value in php
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
Example 5: php sort array remove keys
$arr = array(1, 2, 3);
unset($arr[0]);
$arr = array_values($arr);
print_r($arr);