Reputation: 441
I am trying to figure out why my code wont work as i expect. I have an array:
$persons = array(
0 => array(
'person' => 'John',
'children' => array('Eve', 'Mark', 'Alto')
),
1 => array(
'person' => 'Susy',
'children' => array('Ruby', 'Adam', 'Tõnu')
)
);
Loop the array and sort childrens alphabetically
foreach( $persons as $person ) {
usort($person['children'], function( $a, $b ) {
return strcmp( $a, $b );
});
var_dump($person['children']); //shows children array items alphabetically ordered
}
But after foreach chidrens are still in starting order
var_dump($persons); //shows that children names are not ordered alphabetically
Thank you for your time
Upvotes: 1
Views: 2936
Reputation: 15374
The foreach
loop is creating what is effectively a copy of the array value inside the loop. The copy is sorted but not altering the original array. To do so you can make it a reference with &
:
foreach ($persons as &$person) {
From the documentation:
On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one... In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Another way to reference the arrays directly is to iterate over the indexes and reference the elements:
for ($i = 0; $i < count($persons); $i++) {
usort($persons[$i]['children']), function($a, $b) {
return strcmp($a, $b);
});
}
Upvotes: 2