In PHP, sometimes, it is asked to convert an Array to a String. PHP offers built-in methods to convert Array to a String. We can decide any of these methods for this task according to our preferences.
This article will explain two methods to convert Array to String in PHP. There will be example codes along with the output for better understanding.
Following are the two inbuilt functions of PHP to convert an Array into a String.
Table of Contents
1. implode( ) Function
implode( ) method is used for joining Array element in PHP. It takes only one Array at a time for conversion to string. The working of implode function is quite similar to that of the join( ) method. The syntax for the implode( ) function is given by:
implode( $separator, $array )
The separator parameter is optional. This command will return all the elements of Array concatenated in the same order, just like they were placed initially in Array.
We can use PHP explode( ) function for string to array conversion.
a) Indexed Array
This is the example with indexed array.
<?php $fruits = array('Apple', 'Mango', 'Orange', 'Strawberry', 'Kiwi', 'Melon', 'Apricot'); $fruits_list = implode("- ", $fruits); echo $fruits_list; ?>
b) Associative Array
Following is the example for associative array.
<?php $fruits = array('Apple' => 'Autumn', 'Mango' => 'Summer', 'Orange' => 'Winter', 'Strawberry' => 'Spring'); $fruits_list = implode("- ", $fruits); echo $fruits_list; ?>
c) Multidimensional Array
We are using multidimensional array in the example.
<?php $fruits = array("Welcome", "to", "CodeLeaks"); $fruits_list = implode(" ", $fruits); echo $fruits_list; ?>
2. json_encode( ) Function
json_encode( ) is a built-in method used to return json form of the values. It takes one array at a time. The syntax is given as:
json_encode( $value, $option, $depth )
Usually, JSON reads data from a web server, and then data is displayed on a web page.
<?php $sample = array( "Weather" => "Beautiful", array("E"=> "Enjoy", "T" => "this", "W" => "Weather" )); $json = json_encode($sample); echo ($json); ?>
In this article, examples of both functions are explained to understand the concept. Both of these methods can be used to convert Array into a string. This decision depends on our requirements and available resources. I hope it will help you in your PHP development career.