Reputation: 326
Here is the code
$tasks = $project->getTasks();
foreach ($tasks as $key => $task) {
$task['position'] = $space->getPosition();
$task['symbol'] = $space->getSymbol();
}
logically 'position' and 'symbol' should be added in the array 'task'. They get added in fact, but only inside the loop. They disappear outside the loop. Why?
Upvotes: 0
Views: 387
Reputation: 344
Shouldn't it be something like this?
$tasks = $project->getTasks();
foreach ($tasks as $key => $task) {
$tasks[$key]['position'] = $space->getPosition();
$tasks[$key]['symbol'] = $space->getSymbol();
}
Upvotes: 1
Reputation: 7573
PHP foreach loops operate by value
(on a copy of the data) unless otherwise specified. There are two possible solutions
foreach ($tasks as $key => $task) {
$tasks[$key]['position'] = $space->getPosition();
$tasks[$key]['symbol'] = $space->getSymbol();
}
Alternatively,
foreach ($tasks as &$task) {
$task['position'] = $space->getPosition();
$task['symbol'] = $space->getSymbol();
}
See documentation: http://php.net/manual/en/control-structures.foreach.php
Upvotes: 6
Reputation: 227260
This is because when you use foreach
you are getting a copy of the array values. You need to use a reference in the foreach
.
foreach ($tasks as $key => &$task) {
$task['position'] = $space->getPosition();
$task['symbol'] = $space->getSymbol();
}
Note the &
, that tells PHP to use a reference inside the loop.
Upvotes: 1