1

I have the following given associative array, showing me how many items I have of each key.

'story' => 10
'image' => 20
'video' => 30
'audio' => 40

I'm trying to transform the array so I can use the key string inside my value, I want to get the following result

'story' => 'Story (10)'
'image' => 'Image (20)'
'video' => 'Video (30)'
'audio' => 'Audio (40)'

I've tried

I've tried the following method, but it resets the keys to indexes (0, 1, 2, 3)

return array_map(function ($key, $value) {
    return $key . "(" . $value . ")";
}, array_keys($mergedArray), $mergedArray);
0

2 Answers 2

4

Try using array_walk() instead of array_map()

array_walk($mergedArray, function (&$value, $key) { $value = ucwords($key) . "($value)"; });
print_r($mergedArray);

Working demo

Output:

Array
(
    [story] => Story(10)
    [image] => Image(20)
    [video] => Video(30)
    [audio] => Audio(40)
)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, is passing by reference supported in PHP7.X? I mean is it something that will keep existing, or be deprecated?
Yes! it is supported by PHP 7.x. See official documentation.
3
$arr = [
    "story" => 10,
    "image" => 20,
    "video" => 30,
    "audio" => 40
];

foreach($arr as $key => $value) {
    $arr[$key] = ucfirst($key)." (".$value.")";
}

Here is the demo

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.