How to convert an array to a string in PHP?

Use the implode() function to join the values of an array into a string. If you need the complete array with keys, use json_encode().

<?php
$numbers = [1, 2, 5, 12];

echo implode(",", $numbers);
?>

Output:

Tutorials Class - Output Window

1,2,5,12

<?php
$user = ["name" => "Robin", "age" => 25];

echo json_encode($user);
?>

Output:

Tutorials Class - Output Window

{“name”:”Robin”,”age”:25}

Note: If you try echo $array directly, PHP prints the word “Array” and gives a warning “Array to string conversion”. Use one of the functions above instead.

Read more about implode() in PHP implode() Function. To do the opposite, see PHP explode() Function.


Learn more about the similar topics:
Tutorials
PHP Arrays
PHP Array Functions
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
What are the different PHP functions to sort an array?
PHP’s numerically indexed array begins with which position?
Which PHP function inserts an element to the end of an array?
Which PHP function can be used check if variable is an array?
How many types of arrays are available in PHP?
What is the use of array_chunk() function in PHP?
What is the use of in_array() function in PHP?