Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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, blue

Including 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=25

JSON

json_encode() suits data exchange and nested arrays:

<?php
 
echo json_encode(['name' => 'Anna', 'tags' => ['php', 'js']]);

Output:

{"name":"Anna","tags":["php","js"]}

Functions used in this recipe

  • implode — Joins array elements into a string.
  • explode — Splits a string into an array by a separator.

Thanks for reading!

Donate to the site — we work hard for you.