Home » PHP

How to convert array into string in PHP?

In this article, we will learn how to convert an array into string in PHP using PHP's built in function?
Submitted by Abhishek Pathak, on October 27, 2017

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).

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.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.