Reputation: 906
I am having an issue with a foreach statement where I try to add a extra value to the array, it seemed to work fine, but now all of the sudden it no longer works.
When I do a var_dump inside the for loop of the value added to $application['agency']
it shows the value but as soon as I leave the for statement the and run var_dump($applications);
it no longer has the values in it.
I am sure i am missing something small but cannot see it. Can anybody please assist?
Code:
foreach($applications as $application) {
if (is_array($application)) {
$agenciessarray=db_select("select agency_name from `agencies` where `agency_id`=".db_quote($application['agency_id']));
//var_dump($agenciessarray);
//echo '<br/>';
$application['agency'] = $agenciessarray[0]['agency_name'];
//var_dump($application['agency']);
//echo '<br/>';
}
}
var_dump($applications);
Result:
array(3) {
[0]=> array(7) {
["application_id"] => string(4) "1002"
["first_names"] => string(6) "asdads"
["surname"] => string(6) "asdasd"
["id_number"] => string(6) "123123"
["cell_number"] => string(4) "sadf"
["email_address"] => string(0) ""
["agency_id"] => string(1) "2"
}
[1]=> array(7) {
["application_id"] => string(4) "1003"
["first_names"] => string(6) "asdads"
["surname"] => string(6) "asdasd"
["id_number"] => string(6) "123123"
["cell_number"] => string(4) "sadf"
["email_address"] => string(0) ""
["agency_id"] => string(1) "2"
}
[2]=> array(7) {
["application_id"] => string(4) "1004"
["first_names"] => string(6) "asdads"
["surname"] => string(6) "asdasd"
["id_number"] => string(6) "123123"
["cell_number"] => string(4) "sadf"
["email_address"] => string(0) ""
["agency_id"] => string(1) "2"
}
}
Upvotes: 0
Views: 54
Reputation: 2698
The problem is that you modify local copy of the $applications
array element. It exists only inside the loop. You need to access the actual variable inside the array.
One of the solutions is to include the array key $k
to the loop and then refer to the array element by it.
foreach($applications as $k => $application) {
// .......
$applications[$k]['agency'] = $agenciessarray[0]['agency_name'];
// .......
}
}
PHP documentation for foreach also recommends a way of doing it by passing variable to the loop by reference. Ex:
foreach($applications as &$application) {
// .......
$application['agency'] = $agenciessarray[0]['agency_name'];
// .......
}
}
Upvotes: 1