How to convert an array into a string using PHP? (PHP array to string conversion)

There might be a situation where we may want to convert an array into a string using PHP. So lets see how can we achieve this desired result. Following are two solutions we can convert an array into a string.(php array to string conversion)

PHP Array to String conversion


Solution 01:


<?php
$fruitNames=array("banana","orange","guava","apple");
$fruitNamesAsString=""; // Here I have declared a blank (empty) variable name
foreach($fruitNames as $fname){
                $fruitNamesAsString.=$fname.", ";
}
//After the completion of the for each loop the variable name $fruitNamesAsString contains an extra comma at the end of the value and we need to omit it.
$fruitNamesAsString=rtrim(trim($fruitNamesAsString),",");
echo $fruitNamesAsString;
?>
output: banana, orange, guava, apple

Solution 02

<?php
// We are going to use PHP function implode
$fruitNames=array("banana","orange","guava","apple");
$fruitNamesAsString=implode(",",$fruitNames);
echo $fruitNamesAsString;
?>
output: banana, orange, guava, apple

How to convert an array into a string using PHP? (PHP array to string conversion) How to convert an array into a string using PHP? (PHP array to string conversion) Reviewed by Pixel Stream on December 09, 2019 Rating: 5

No comments:

Powered by Blogger.