views:

32

answers:

4
$array = array('lastname', 'email', 'phone');

How do I run foreach for this array and write updated value to its place?

Like:

foreach ($array as $item) {
   // do something
   // replace old value of this item with a new one
}

Example:

foreach ($array as $item) {
    if (item == 'lastname')
        $item = 'firstname';
        // replace current $item's value with a 'firstname'
}

Array should become:

$array = array('firstname', 'email', 'phone');
+2  A: 

In your example, a foreach loop would seem unnecessary if you know exactly what key maps to lastname, but if you need to you can still loop through the values. There are two very common ways: set the value according to the key:

foreach ($array as $key => $value) {
    if ($value == 'lastname') {
        $array[$key] = 'firstname';
    }
}

Or (PHP 5 only) use references:

foreach ($array as &$item) {
    if ($item == 'lastname') {
        $item = 'firstname';
    }
}

// Clean up the reference variable
unset($item);
BoltClock
+1  A: 

You could do it like this:

foreach ($array as $key => $item) {
   $array[$key] = "updated item";
}
xil3
+4  A: 

An alternative is to loop by reference:

foreach ($array as &$value) {
    $value = strtoupper($value);
}
unset($value);// <=== majorly important to NEVER forget this line after looping by reference...
Wrikken
+1 for highlighting the significance of the unset()
Mark Baker
Happy
@Happy: it's a reference, see http://php.net/manual/en/language.references.php
Wrikken
@Wrikken, can you describe in two words? that page is too big
Happy
2 words? There is a _reason_ the page is big. In short: 2 or more variable names (in this case `$array[<particular key>]` and `$item`) will point to the same value in memory, `unset()`ing one will keep the value intact for the other, changing one will mean the other will have the same changed data.
Wrikken
+1  A: 
foreach ($array as $i => $value) {
    if ($value == 'lastname')
        $array[$i] = 'firstname';
}
Robert