Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort by keep keys and keep value order?

Tags:

php

I have an

$a = array(9=>"a",8=>"c",5=>"d");

I want to sort the only keys of array $a and keep order of values.

so it will be array(5=>"a",8=>"c",9=>"d");

How Could I DO in php array?

like image 779
sophie Avatar asked Oct 30 '25 05:10

sophie


1 Answers

Sorting the keys, but keep the values in order is not possible by just ordering, because it would result in a new array. This is also the solution: Create a new array

$keys = array_keys($a);
sort($keys);
$result = array_combine($keys, array_values($a));
like image 160
KingCrunch Avatar answered Nov 01 '25 20:11

KingCrunch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!