How to assign values to an associative array in php?

Asked

Viewed 1,760 times

2

In an array, for example:

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

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 local variable not used; (unused local variable '$b')

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

2 answers

2


Assign by passing the key, this is for both associative and numerical arrays. So just match the key ($key) with the array and assign the new value.

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

print_r($arr);

1

There is another way yet, which is by using reference.

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

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

By using the sign &$value, the value passed to the current of the foreach will be pointing to the original value of the array, however as reference. If you change it, the current value pointed will also be changed.

Note that at the end I used a unset, because if it did not do so, by changing the value $value outside the foreach, the last element of $arr would be modified.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.