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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |