String replace all items in array PHP

AJFMEDIA picture AJFMEDIA · Feb 18, 2011 · Viewed 48.4k times · Source

I would like to do a string replacement in all items in an array. What I have is:

$row['c1'] = str_replace("&", "&", $row['c1']);
$row['c2'] = str_replace("&", "&", $row['c2']);
$row['c3'] = str_replace("&", "&", $row['c3']);
$row['c4'] = str_replace("&", "&", $row['c4']);   
$row['c5'] = str_replace("&", "&", $row['c5']);
$row['c6'] = str_replace("&", "&", $row['c6']);
$row['c7'] = str_replace("&", "&", $row['c7']);   
$row['c8'] = str_replace("&", "&", $row['c8']);
$row['c9'] = str_replace("&", "&", $row['c9']);
$row['c10'] = str_replace("&", "&", $row['c10']); 

How can I achieve this with less code? I thought a foreach statement would work, e.g.:

$columns = array($row['c1'], $row['c2'], $row['c3'], $row['c4'], $row['c5'], $row['c6'], $row['c7'], $row['c8'], $row['c9'], $row['c10']);

foreach ( $columns as $value){
   $value   = str_replace("&", "&", $value);
}

But it doesn't work.

Answer

netcoder picture netcoder · Feb 18, 2011

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.