String replace all items in array PHP

陌路散爱 提交于 2019-12-04 01:18:01
netcoder

Just do:

$row = str_replace("&", "&", $row);

Note: Your foreach doesn't work because you need a reference, or use the key:

foreach ( $columns as &$value) { // reference
   $value  = str_replace("&", "&", $value);
}
unset($value); // break the reference with the last element

Or:

foreach ($columns as $key => $value){
   $columns[$key]  = str_replace("&", "&", $value);
}

Although it is not necessary here because str_replace accepts and returns arrays.

You should call it by reference, otherwise foreach creates a duplicate copy of $value

foreach ( $columns as &$value)

mr.baby123

Another solution to is to use PHP array_walk like this:

function custom_replace( &$item, $key ) {
   $item = str_replace('22', '75', $item);
} 

// Init dummy array.
$columns = array('Cabbage22', 'Frid22ay', 'Internet', 'Place22', '22Salary', '22Stretch', 'Whale22Inn');

// Print BEFORE.
echo 'Before: ';
print_r($columns);

// Make the replacements.
array_walk($columns, 'custom_replace');

// Print AFTER.
echo 'After:';
print_r($columns);

Output:

Before: Array
(
    [0] => Cabbage22
    [1] => Frid22ay
    [2] => Internet
    [3] => Place22
    [4] => 22Salary
    [5] => 22Stretch
    [6] => Whale22Inn
)
After: Array
(
    [0] => Cabbage75
    [1] => Frid75ay
    [2] => Internet
    [3] => Place75
    [4] => 75Salary
    [5] => 75Stretch
    [6] => Whale75Inn
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!