4

say I have an array in php like this

$info['name'] = 'test %value%';
$info['city'] = 'city test %value%';
$info['other'] = '%value% city test';

all I want to do is loop through this array and replace all the instances of %value% with a supplied string, saving it into the same array.

What would be the best way to do that? :)

Thanks

2 Answers 2

15
foreach ($info as $key => $value)
  $info[$key] = str_replace('%value%', 'MyValue', $value);

Demo: http://ideone.com/65F3L

Sign up to request clarification or add additional context in comments.

1 Comment

If you want to only replace instances where the entire $value equals your search criteria, rather than instance within the strong, then just wrap the second line in: if ($value == "%value%") {
4

This seems to be the cleanest way to me, but it requires PHP 5.3 or higher:

$info = array_map(function($x) use ($newValue){ 
    return str_replace('%value%', $newValue, $x);
}, $info);

Codepad

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.