PHP Basics

PHP: How to convert an Array into a string?

In some cases, we may want to convert an array into a string. There are plenty ways we can achieve the result. Lets learn about most effective ones.

Convert An Array To String

We can convert an array into a string in following two ways. First one – implement our own logic and second one – to use PHP’s predefined function.

Solution 1

Loop through the array and append each array element to a string variable with a separator like “,” and remove the last comma.

Example

<?php

$fruitNames=array(“apple”,”orange”,”grape”,”guava”,”mango”);

$fruitNamesString=””; // Here we have declared a variable and assigned empty string value

// loop through each array element and append to empty string.

foreach($fruitNames as $fruitName){

// Here we are appending each array element to the string variable.

$fruitNamesString.=$fruitName.”, “;

}

$fruitNameString=trim(rtrim(trim($fruitNameString),”,”)); // Here we have removed the comma at the last.

echo $fruitNameString;

?>

 

Output

apple, orange, grape, guava, mango

Solution 2

Using PHP’s predefined function “implode

Syntax

implode(separator,array)

Example

<?php

$fruitNames=array(“apple”,”orange”,”grape”,”guava”,”mango”);

$fruitNamesString=implode(“, “,$fruitNames);

echo $fruitNamesString;

?>

 

Output

apple, orange, grape, guava, mango

Note: instead of comma, if you want space then all you have to do is, use space as separator.

Example

<?php

$fruitNames=array(“apple”,”orange”,”grape”,”guava”,”mango”);

$fruitNamesString=implode(” “,$fruitNames);

echo $fruitNamesString;

?>

 

Output

apple orange grape guava mango