Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Stupid Beginner Array Sort Question

1. ## Stupid Beginner Array Sort Question

I have an array
PHP Code:
``` \$array['A']=5; \$array['B']=2; \$array['C']=3;  ```
How to achieve the following sort of \$array? (sort by it's value)
PHP Code:
``` \$array['B'] \$array['C'] \$array['A']  ```
and of course the other way

PHP Code:
``` \$array['A'] \$array['C'] \$array['B']  ```

Usually i do it a complicated way (by foreach, init new array and and so on). But there have to be a more easy way right?

Thats my current function by the way
PHP Code:
``` function sortByKey(\$arr=false,\$sort='desc'){     foreach(\$arr as \$name=>\$val){         \$n[].=\$name;         \$v[].=\$val;     }     if(\$sort==='asc'){         array_multisort(\$v,SORT_ASC,\$n);     }else{         array_multisort(\$v,SORT_DESC,\$n);     }     for(\$i=0; \$i<count(\$n); \$i++){     \$ba[\$n[\$i]]=\$v[\$i];}     return \$ba; }  ```
which does exactly what i need. But there must be a better way.

2. PHP Code:
``` <?php \$array['A']=5; \$array['B']=2; \$array['C']=3; asort(\$array); echo '<pre>'; print_r(array_keys(\$array)); echo '</pre>'; arsort(\$array); echo '<pre>'; print_r(array_keys(\$array)); echo '</pre>'; ```

3. ## Users who have thanked benanamen for this post:

Labrar (Jan 19th, 2019)