'Merge key and value of array index [duplicate]

I have an array as follows:

['foo'=>'bar','baz'=>'bat']

im trying to determine an elegant way (not using a standard forloop, prefer learning php array functions) to result in:

['foo: bar','baz: bat']

as you can see, the key and the value are joined together separated by a :

seems pretty simple, just cant figure out how to do this using an array function format. just trying to gain experience in php functions. i imagine its using implode somehow but im trying to figure out how to join the key and value together into one.

i'm on php 8.0



Solution 1:[1]

Another way using array_map():

$arr = ['foo'=>'bar','baz'=>'bat'];
$combine = array_map(fn($k, $v) => "$k: $v", array_keys($arr), array_values($arr));
print_r($combine);

Output

Array
(
    [0] => foo: bar
    [1] => baz: bat
)

Solution 2:[2]

$arr = [ 'foo' => 'bar', 'baz' => 'bat' ];

$result = [];

array_walk($arr, function ($value, $key) use (&$result) {
  $result[] = "$key: $value";
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Syscall
Solution 2 lukas.j