Home » PHP » PHP Examples

PHP | Create comma delimited string from an array without using library function

Creating a comma delimited string from an array: Here, we are going to learn how we can create a comma delimited string from a given array without using any library function in PHP?
Submitted by Bhanu Sharma, on August 11, 2019

Given an array and we have to create a comma delimited string from the array without using library function.

Example:

    Input: 
    array("Google","Bing","Yahoo!","DuckDuckGo")

    Output:
    comma delimited string: "Google, Bing, Yahoo!, DuckDuckGo"

PHP code to create comma delimited string from an array without using library function

<?php
//PHP code to reverse the string without 
//using library function

//function definition 
//it accepts an array and returns comma delimited string
function create_string($arr){
    //variable to store the string
    $str = '';
    
    for($i = 0; $i < count($arr); $i++){
        $str .= $arr[$i];
        if($i < (count($arr) -1)){
          $str .= ", ";
        }
    }
    
    //return the result i.e. comma delimited string
    return $str;
    
}

//main code i.e. function calling
$arr = array("New Delhi","Mumbai","Chennai","Banglore");
$result = create_string($arr);
echo "array is: ". "<br/>";
print_r($arr);
echo "comma delimited string: " .$result ."<br/>";

$arr = array("Google","Bing","Yahoo!","DuckDuckGo");
$result = create_string($arr);
echo "array is: ". "<br/>";
print_r($arr);
echo "comma delimited string: " .$result ."<br/>";
?>

Output

array is: 
Array
(
    [0] => New Delhi
    [1] => Mumbai
    [2] => Chennai
    [3] => Banglore
)
comma delimited string: New Delhi, Mumbai, Chennai, Banglore
array is: 
Array
(
    [0] => Google
    [1] => Bing
    [2] => Yahoo!
    [3] => DuckDuckGo
)
comma delimited string: Google, Bing, Yahoo!, DuckDuckGo

Explanation:

We use for loop to read the array and store it into a string delimited by a (,) whenever one value in the array is printed. This continues until we reach the last string to avoid printing another comma at the end of the list.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




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.