For example, to echo a single element of an array, you can convert the array to a string and print it on the screen.
In this tutorial, you will learn how to convert a PHP array to a string.
Using PHP Implode() Function
The PHP implode() function is a common method when working with arrays. It allows you to join elements in an array using a specified delimiter. The function returns the elements joined in a string format. Hence the function is handy when converting an array to a string.
NOTE: The function also provides the join() method as an alias.
The syntax of the function is as shown below:
The above function takes two arguments: a delimiter (also known as a separator) and an array, respectively.
The following example shows you how to convert an array to a string using the implode function.
This allows the function to return each element in the array as a single sentence.
The example output is as shown:
NOTE: PHP will return a notice message if you run the echo method against an array.
You can also use another delimiter in the method as:
The resulting output is as shown:
Using PHP json_encode() Function
The other way to convert an array to a string is the json_encode() function. This built-in method allows you to convert an array to a JSON string.
Take a look at the example shown below:
$mean = array("MongoDB", "Express", "Angular", "NodeJS");
$json_data = json_encode($mean);
print_r ($json_data);
?>
Once we run the above code, we should see the array in JSON format as shown:
Using PHP Serialize() Method
The serialize() method allows you to convert an array to a byte-stream string. Consider the example shown below:
Running the code should return a serialized string as:
Conclusion
This guide gives you the basics of converting a PHP array into a string using built-in methods.
Stay tuned for more tutorials.