Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does asort work?

Tags:

arrays

php

asort

I was having a look over some of my old work and saw that the asort function would have worked perfectly for some of the uses I needed, although I attempted an extremely different and longwinded way.

So my question is exactly, how does asort maintain association when sorting? I thought an array can be sorted by key, or by value, is there a third sorting pivot?

like image 591
siame Avatar asked Mar 31 '26 22:03

siame


2 Answers

The "third pivot" is the actual location in memory/array.
You will see it clearly when doing a foreach on the following two arrays, which are the same, but have different order:

$x1=array('mmm'=>'mmm','bbb'=>'bbb','ccc'=>'ccc');
$x2=array('ccc'=>'ccc','bbb'=>'bbb','mmm'=>'mmm');

foreach($x1 as $k=>$v) echo "{$k} {$v}";
foreach($x2 as $k=>$v) echo "{$k} {$v}";

doing the default asort on those two arrays will result in both cases in:

$x1=array('bbb'=>'bbb','ccc'=>'ccc','mmm'=>'mmm');
$x2=array('bbb'=>'bbb','ccc'=>'ccc','mmm'=>'mmm');
like image 52
Itay Moav -Malimovka Avatar answered Apr 03 '26 13:04

Itay Moav -Malimovka


From the manual :

asort — Sort an array and maintain index association

So, for example :

  • Asort will just sort by value in ascending way keeping the index=>value association.
  • Arsort is the same but in desc way.

The manual is pretty clear on Array sorting function here.

Basic function only sort by key or values but there are options:

  • index->value association maintained or not
  • Use of a custom function for sorting or not
  • Asc or Desc
  • case sensitive or not
like image 34
Shikiryu Avatar answered Apr 03 '26 14:04

Shikiryu



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!