How to convert array into string in PHP?

Given an array. Learn, how to convert it into a string?
Submitted by Abhishek Pathak, on October 27, 2017 [Last updated : March 13, 2023]

PHP - Converting Array to String

The server-side scripting language for web, PHP supports the array data type which has very interesting use cases to store data in the program. As a web developer it is important to know the various operations on array data type to code highly efficient web scripts. PHP provides with lots of in-built methods to perform operations on array.

In this article, we will learn how to convert an array into String using PHP's built in function. Just like the front-end JavaScript, PHP has also, join() method which joins each and every element of the array into a nicely formatted string with a separator. The separator separates the elements of array from each other in the output string using a character which can be anything, and by default is , (comma).

PHP code to convert an array to a string

Here's an example which uses this PHP method effectively

<?php
$favouriteColors = array("Red", "Yellow", "Blue");
$string = join(',', $ favouriteColors);
echo 'Favourite Colors are: ' . $string;
?>

In this code, we have a favouriteColors array which contains the string elements. Then we declare a string variable and in this store the result of join operation performed on array, favouriteColors. It will output in the order of elements, , separated values.

Favourite Colors are: Red, Yellow, Blue

This is easy with PHP's inbuilt function but we can also write a code to create a string from array.

Code

<?php
$string = ''; //Empty string initally.

foreach ($array as $key => $value) {
	$string .= ",$value"; //Add into string value
}
$string = substr($string, 1); //To remove the first , from first element
?>

It works same as the join function. We iterate the array using a loop and in the string variable store the string that joins the element preceded by , symbol. Finally, we remove the first , using the substr() method that will return the string from index 1 to string length, i.e, discard the first , in the string.

This is how we join the elements of an array into a string in PHP? Share your thoughts in the comments below.

PHP String Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.