pastet89;10899557 wrote:Hi all, I have a small task that has to be solved:
I tried this code:
$array = array(
"123", "1a23a", "1b23b"
);
foreach($array as $val) {
str_replace("2", "", $val);
}
...but nothing happaned. Do you have any ideas?
Pastet89, you were so close 🙂
try:
$array = array(
"123", "1a23a", "1b23b"
);
foreach($array as &$val) {
$val = str_replace("2", "", $val);
}
echo '<pre>'.print_r($array, true);
Output:
Array
(
[0] => 13
[1] => 1a3a
[2] => 1b3b
)
Two things went wrong in your initial code..
a) you did not assign anything to be equal to str_replace... so in this case, reassign $val towhat str_replace will give you...
b) If you want to manipulate the direct array keys' values, you use an ampersand (&) infront of the value (passing a value by reference), otherwise, you are manipulating a copy of the array's values, meaning that once you are finished with foreach, the orginal array's values are untouched.
@wtg21.org, it is not neceesary to preg here.. see this thread.