Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge key and value of array index

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading