0

I promise you I've had a look at the many existing SO Qs about PHP sorting, including this mega one

I've got a PHP associative array, with strings as keys. Each value is an array of integers. I want to sort each array of integers, in simple ascending numerical order. I'm convinced this should be easy, and I've found enough examples that I think I should be doing the right thing, but it's not quite working, so there's a typo or I'm an idiot or something...

PHP:

//Each fruit corresponds to an array (series) of integers
$data = [
    'banana' => [
        1,3,2
    ],
    'orange' => [
        5,1,3
    ]
];

echo "Before sort:\n";
var_dump($data);

//For each fruit, I want to order the numbers
foreach ($data as $key => $series)
{
    //Sort array of integers
    sort($series);

    //NB I wasn't sure about value/reference details of foreach loops, so I also tried
    //retrieving a series into a variable, sorting, and then reassigning back to the same key
}

echo "\n\nAfter sort:\n";
var_dump($data);

Output:

Before sort:
array(2) {
  'banana' =>
  array(3) {
    [0] =>
    int(1)
    [1] =>
    int(3)
    [2] =>
    int(2)
  }
  'orange' =>
  array(3) {
    [0] =>
    int(5)
    [1] =>
    int(1)
    [2] =>
    int(3)
  }
}


After sort:
array(2) {
  'banana' =>
  array(3) {
    [0] =>
    int(1)
    [1] =>
    int(3)
    [2] =>
    int(2)
  }
  'orange' =>
  array(3) {
    [0] =>
    int(5)
    [1] =>
    int(1)
    [2] =>
    int(3)
  }
}

As you can see, in the output the inner arrays of integers have not been sorted. What am I doing wrong? (PHP 5.5.9, Windows 7)

Community
  • 1
  • 1
frumious
  • 1,551
  • 17
  • 24

1 Answers1

2

Use a reference &:

foreach ($data as $key => &$series)
{
    //Sort array of integers
    sort($series);
    // OR
    // sort($data[$key]);
}
Korikulum
  • 2,359
  • 19
  • 24
  • Ah, that does work, fast work! I didn't do that because I found at least one commenter recommending against it, in general, because things behaved "unexpectedly". Can't find it now. – frumious Jun 03 '14 at 23:40
  • @frumious Hm, can't say I've ever heard of that... maybe in some cases. – Korikulum Jun 03 '14 at 23:41
  • I also tried $temp = $data[$key]; sort($temp); $date[$key] = $temp - would you have expected that to work? It didn't seem to. EDIT Actually it is now, wonder what I was doing wrong... – frumious Jun 03 '14 at 23:41
  • @frumious `sort($data[$key]);` – Korikulum Jun 03 '14 at 23:44