How to Convert an Array to a String in PHP

  1. Use Implode() Function to Convert an Array to a String in PHP
  2. Use Json_encode() Function to Convert an Array to a String in PHP
  3. Use Serialize() Function to Convert an Array to a String in PHP

In this article, we will introduce methods to convert an array to a string.

  • Using implode() function
  • Using json_encode() function
  • Using serialize() function

Use Implode() Function to Convert an Array to a String in PHP

The implode() function converts an array to a string. It returns the string that has all the elements of the array. The correct syntax to use this function is as follows

implode($string, $arrayName);

The variable $string is the separator to separate the elements of the array. The variable $arrayName is the array to be converted.

<?php   
$arr = array("This","is", "an", "array");  
$string = implode(" ",$arr);  
echo "The array is converted to the string.";
echo "\n";
echo "The string is '$string'";
?>

Here we have passed a white space string as a separator to separate the elements of the array.

Output:

The array is converted to the string.
The string is 'This is an array'

Use Json_encode() Function to Convert an Array to a String in PHP

The json_encode() function is used to convert an array to a json string. json_encode() also converts an object to json string.

json_encode( $ArrayName );  

The variable ArrayName shows the array to be converted to a string.

<?php
   $array = ["Lili", "Rose", "Jasmine", "Daisy"];
   $JsonObject = json_encode($array);
   echo "The array is converted to the Json string.";
   echo "\n"; 
   echo"The Json string is $JsonObject";
?>
Warning

The function accepts the array as a parameter and it returns the string.

Output:

The array is converted to the Json string.
The Json string is ["Lili","Rose","Jasmine","Daisy"]

Use Serialize() Function to Convert an Array to a String in PHP

The serialize() function converts an array to a string effectively. It also returns the index value and string length along with each element of the array.

serialize($ArrayName);

The function accepts the array as a parameter and returns a string.

<?php
   $array = ["Lili", "Rose", "Jasmine", "Daisy"];
   $JsonObject = serialize($array);
   echo "The array is converted to the Json string.";
   echo "\n"; 
   echo"The Json string is $JsonObject";
?>

Output:

The array is converted to the Json string.
The Json string is a:4:{i:0;s:4:"Lili";i:1;s:4:"Rose";i:2;s:7:"Jasmine";i:3;s:5:"Daisy";}

The output is an array with the description that tells

  • The number of elements in an array a:4, the array has 4 elements
  • The index of each element and the element length i:0;s:4:"Lili";

Related Article - PHP Array

  • How to Sort an Array of Associative Arrays by Value of a Given Key in PHP
  • How to Check Whether an Array Is Empty in PHP
  • Related Article - PHP String

  • How to Check Whether an Array Is Empty in PHP
  • comments powered by Disqus