Verification: a143cc29221c9be0

Php assoc array to string

Using two arrays

A quick overview of how str_replace works with arrays first:

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

The search and replace parameters can either be strings or arrays. If both are arrays, the string in index 0 in the first array will be replaced with the string in index 0 in the second array, index 1 with index 1 and so on. The example below replaces ‘quick’ with ‘hungry’, ‘fox’ with ‘wolf’ and so on.

$string = "The quick brown fox jumped over the lazy dog";
$search = array('quick', 'fox', 'jumped over', 'dog');
$replace = array('hungry', 'wolf', 'ate', 'mouse');
echo str_replace($search, $replace, $string);

Here is the resulting output:

The hungry brown wolf ate the lazy mouse

Using an array and a string

If the search parameter is an array and the replace parameter a string, everything matching each of the array items in the source string will be replaced with the replace parameter.

Using the same example code as the above, to replace all the items in the $search array with [replaced] do this:

echo str_replace($search, "[replaced]", $string);

Which would result in this:

The [replaced] brown [replaced] [replaced] the lazy [replaced]