hcb
hcb

Reputation: 326

I am unable to add a key value pair in a PHP array

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

Answers (3)

Andizer
Andizer

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

CollinD
CollinD

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

gen_Eric
gen_Eric

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

Related Questions