Miguel Stevens
Miguel Stevens

Reputation: 9201

PHP Map to use key in value for associative array

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);

Upvotes: 1

Views: 415

Answers (2)

Vinay Patil
Vinay Patil

Reputation: 746

$arr = [
    "story" => 10,
    "image" => 20,
    "video" => 30,
    "audio" => 40
];

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

Here is the demo

Upvotes: 3

MH2K9
MH2K9

Reputation: 12039

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)
)

Upvotes: 4

Related Questions