I have a 2D array that looks like this:
array(2) {
[45]=>
array(5) {
[0]=>
int(2)
[1]=>
int(5)
[2]=>
int(1)
[3]=>
int(3)
[4]=>
int(4)
}
[42]=>
array(5) {
[0]=>
int(5)
[1]=>
int(4)
[2]=>
int(3)
[3]=>
int(2)
[4]=>
int(1)
}
}
The key values of the outer array are numerical, but do not start at 0, and are not sequential. I want to sort the outer array by ascending keys, and the inner arrays by ascending values, so I try this:
ksort($arr);
foreach ($arr as $a) {
sort($a);
}
var_dump($arr);
Which sorts the outer array as expected, but doesn’t seem to touch the inner arrays at all:
array(2) {
[42]=>
array(5) {
[0]=>
int(5)
[1]=>
int(4)
[2]=>
int(3)
[3]=>
int(2)
[4]=>
int(1)
}
[45]=>
array(5) {
[0]=>
int(2)
[1]=>
int(5)
[2]=>
int(1)
[3]=>
int(3)
[4]=>
int(4)
}
}
Why is this, and how can I achieve what I want? I think it’s something to do with the array being nested, because the following works as expected:
$test = array(5,2,3,1,4);
sort($test);
var_dump($test);
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
foreachiterates over a copy of the array. If you want to modify the actual values, you have to reference them:From the documentation: