How to Convert Array to String in PHP?

Last Updated : 02 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In PHP, Arrays are used to store multiple values in a single variable. However, sometimes we need to convert these arrays into strings:

  • To display array data in a readable format.
  • To join array items into a single sentence or list.
  • To use the array data where only strings are accepted.
  • To prepare data for storage in databases or files.

Common Methods to Convert Array to String in PHP

1. Using implode() Function

The most common and straightforward method to convert an array to a string is the implode() function. The implode() function joins array elements into a single string separated by the specified separator.

Now, let us understand with the help of the example:

PHP
<?php
$fruits = ['apple', 'banana', 'orange'];
$string = implode(", ", $fruits);
echo $string;

?>

Output
apple, banana, orange

2. Using join() Function

join() means the same as implode(). Both work in exactly the same way.

PHP
<?php
  $fruits = ['apple', 'banana', 'orange'];
$string = join(" | ", $fruits);
echo $string;
?>

Output
apple | banana | orange

3. Using serialize() Function

serialize() converts the entire array (including keys and nested arrays) into a storable string representation. It is useful for storing or transmitting the complete array structure.

Now, let us understand with the help of the example:

PHP
<?php
   $array = ['name' => 'anjali', 'age' => 30];
$serialized = serialize($array);
echo $serialized;
?>

Output
a:2:{s:4:"name";s:6:"anjali";s:3:"age";i:30;}

4. Using json_encode() Function

json_encode() converts an array into a JSON-formatted string. This method is very popular for data interchange between PHP and JavaScript or APIs.

PHP
<?php
   $array = ['name' => 'anjali', 'age' => 30];
$json = json_encode($array);
echo $json;
?>

Output
{"name":"anjali","age":30}

Best Practices

  • Use implode() for simple arrays when you want a readable list.
  • Use serialize() for storing PHP-specific array data (note: only PHP can unserialize it).
  • Be careful about the types of data and special characters when changing arrays into strings.
  • For multidimensional arrays, prefer serialize().

Conclusion

Converting arrays to strings in PHP is a common and essential task that can be accomplished in various ways depending on the specific need. For simple lists and readable output, functions like implode() or join() are straightforward and effective. When it comes to storing or transmitting complex array structures, especially multidimensional arrays, serialize() and json_encode() provide reliable solutions, with json_encode() also offering great compatibility for data exchange with other systems.


Next Article

Similar Reads