How to assign values to an associative array in php?

2

In an array, for example:

$arr = array('item1', 'item2' ... 'itemN');

I want to assign a value to each item. For this, I tried a foreach:

foreach($arr as $a => $b)
    $b = 4;

but is informed by the IDE (phpStorm) that the unused local variable; (unused local variable '$b')

How do I assign a value to an item in this array ??

    
asked by anonymous 21.09.2016 / 16:44

2 answers

2

Assign by passing the key, this is for both associative and numeric arrays. Then just combine the key ( $key ) with the array and assign the new value.

foreach($arr as $key => $value){
    $arr[$key] = 'novo valor';
}

print_r($arr);
    
21.09.2016 / 16:54
1

There's still another way, which is using reference.

foreach ($arr as $key => &$value) {
    $value = 'novo valor';
}

unset($value); // Tem que apagar, pois o último sempre fica como referência.

When using the &$value sign, the current value of the iteration of foreach will be pointing to the original value of array , but as a reference. If you change it, the current value you pointed to will also change.

Note that at the end I used a unset , otherwise I would change the value $value out of foreach , the last element of $arr would be modified.

    
21.09.2016 / 17:04