$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');
From stackoverflow
Happy
-
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);From BoltClock -
You could do it like this:
foreach ($array as $key => $item) { $array[$key] = "updated item"; }From xil3 -
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...Mark Baker : +1 for highlighting the significance of the unset()Happy : what is **&** for, inside "&$value"?Wrikken : @Happy: it's a reference, see http://php.net/manual/en/language.references.phpHappy : @Wrikken, can you describe in two words? that page is too bigWrikken : 2 words? There is a _reason_ the page is big. In short: 2 or more variable names (in this case `$array[]` 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. From Wrikken -
foreach ($array as $i => $value) { if ($value == 'lastname') $array[$i] = 'firstname'; }From Robert
0 comments:
Post a Comment