0

I've ready read various questions on here about sorting arrays by values in PHP but they don't seem to sort the very simple array I have.

Array
(
    [area1] => 4.8
    [area2] => 6.1
    [area3] => 3.6
    [area4] => 5.1
)

I'm trying to return an array ordered by values... so in the above example, area3, area1, area4, area2

I've tried asort, but that doesn't seem to work.

Any ideas? I'm sure it must be simple and I'm just missing something. Thanks.

Jack
  • 65
  • 2
  • 9

3 Answers3

1

You can use asort() - This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

$arr = array (
    'area1' => 4.8,
    'area2' => 6.1,
    'area3' => 3.6,
    'area4' => 5.1
);

asort( $arr );

echo "<pre>";
print_r( $arr );
echo "</pre>";

This will result to:

Array
(
    [area3] => 3.6
    [area1] => 4.8
    [area4] => 5.1
    [area2] => 6.1
)

Doc: asort()

Eddie
  • 26,593
  • 6
  • 36
  • 58
1

This should be your solution

$a = ["area1" => 4.8,
    "area2" => 6.1,
    "area3" => 3.6,
    "area4" => 5.1];

asort($a);

var_dump($a);

array(4) { ["area3"]=> float(3.6) ["area1"]=> float(4.8) ["area4"]=> float(5.1) ["area2"]=> float(6.1) }

Jack Skeletron
  • 1,351
  • 13
  • 37
  • Both of the above are absolutely working. Very strange, I'd tried asort already.... obviously typed something wrong. – Jack May 11 '18 at 07:49
  • Did you assign the result of `asort($a)` back into `$a` perhaps? – Qirel May 11 '18 at 07:58
  • @Qirel take a look [at asort manual](http://php.net/manual/en/function.asort.php), the function accepts a variable by reference (&$a in this case) – Jack Skeletron May 11 '18 at 08:14
  • My question was if OP had `$a = asort($a);`, and thus making `$a` a boolean. ;-) I'm well aware the `asort()` is by reference, which is why I asked. – Qirel May 11 '18 at 08:16
  • @Qirel sorry, i didn't get that the question was not for me :) – Jack Skeletron May 11 '18 at 08:17
0

Try the following

<?php

$areas = array(
    "area1" => 4.8,
    "area2" => 6.1,
    "area3" => 3.6,
    "area4" => 5.1
);

asort($areas);
print_r($areas);

?>

Array ( [area3] => 3.6 [area1] => 4.8 [area4] => 5.1 [area2] => 6.1 )

Moose
  • 610
  • 1
  • 14
  • 28