-4

I have an array that needs some modification, I need to add a word before every value. Is there a easy way to do this?

[
'site'=>'some-slug-of-page',
'site'=>'some-slug-new-page',
'site'=>'my-page'
]

needs to be

[
'site'=>'blog/some-slug-of-page',
'site'=>'blog/some-slug-new-page',
'site'=>'blog/my-page'
]
user759235
  • 2,147
  • 3
  • 39
  • 77

2 Answers2

0

For the sake of immutability, I create a new array, reusing the old keys.

$originalArr = [
    'site1' => 'some-slug-of-page',
    'site2' => 'some-slug-new-page',
    'site3' => 'my-page'
];

$newArr = [];

foreach ($originalArr as $key => $value) {
    $newArr[$key] = 'blog/' . $value;   
}
OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
-1
array_walk($arr, function (& $val, $key) { $val = 'blog/' . $val;});
Andrey Yerokhin
  • 273
  • 1
  • 7
  • Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made – Shawn C. Jan 19 '18 at 15:22