How to convert an array to a string
Short answer
implode() joins the elements with a separator:
<?php
echo implode(', ', ['red', 'green', 'blue']);Output:
red, green, blueIncluding the keys
implode() uses only the values. To include the keys, build the parts in a loop:
<?php
$user = ['name' => 'Anna', 'age' => 25];
$parts = [];
foreach ($user as $key => $value) {
$parts[] = "$key=$value";
}
echo implode('&', $parts);Output:
name=Anna&age=25JSON
json_encode() suits data exchange and nested arrays:
<?php
echo json_encode(['name' => 'Anna', 'tags' => ['php', 'js']]);Output:
{"name":"Anna","tags":["php","js"]}