Skip to content
Advertisement

Replace string in an array with PHP

How can I replace a sub string with some other string for all items of an array in PHP?

I don’t want to use a loop to do it. Is there a predefined function in PHP that does exactly that?

How can I do that on keys of array?

Advertisement

Answer

$array = array_map(
    function($str) {
        return str_replace('foo', 'bar', $str);
    },
    $array
);

But array_map is just a hidden loop. Why not use a real one?

foreach ($array as &$str) {
    $str = str_replace('foo', 'bar', $str);
}

That’s much easier.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement