Skip to content
Advertisement

Best way to convert array into string with PHP keeping Keys and Values

I’ve an array:

[
  "Cuzco" => "Peru"
  "Lima" => "Peru"
]

I need the output to be: Cuzco (Peru) + Lima (Peru)

Can I use http_build_query for this? I tried

http_build_query($array, " + ")

Advertisement

Answer

Put all the key (value) strings in an array, then call implode() to combine them.

$a = [];
foreach ($array as $key => $value) {
    $a[] = "$key ($value)";
}
$result = implode(' + ', $a);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement