Reputation: 1816
How can I replace all the values of an array with a single $string
.
For example I have this :
$string = "myString";
$array = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
);
I want to output this :
$replacedArray = array(
'key1' => 'myString',
'key2' => 'myString',
'key3' => 'myString',
);
How can I replace all the values of an array with a $string
.
Upvotes: 0
Views: 68
Reputation: 490233
Use array_map()
and return 'myString'
. This will give you a new array.
$replacedArray = array_map(function() { return 'myString'; }, $array);
If you want to change them in place, you could use a loop or any other function that mutates the original array.
Upvotes: 4
Reputation: 68476
Use an array_walk()
[This function modifies your original array itself]
array_walk($array, function(&$v) use($string) { $v = $string;});
$replacedarray = $array; //<--- If you want the results in another array.
Go with Alex's answer, If you want the result in another variable.
Upvotes: 2