Home > OS >  Merge key and value of array index
Merge key and value of array index

Time:02-17

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

CodePudding user response:

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
)

CodePudding user response:

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

$result = [];

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