0

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.

2 Answers 2

4

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.

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

Comments

2

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.

Demonstration

2 Comments

Could you use it as a variable instead?
I don't get you .. sorry ? Did you check the demo ? If you want the results in another variable , check alex's answer. My answer modifies the original array itself.

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.