Making a comma-delimited string from an exhibit: Here, we will figure out how we can make a comma-delimited string from a given cluster without utilizing any library function in PHP?
Given a cluster and we need to make a comma-delimited string from the exhibit without utilizing library function.
Example:
Input:
array("Google","Bing","Yahoo!","DuckDuckGo")
Output:
comma delimited string: "Google, Bing, Yahoo!, DuckDuckGo"
PHP code to make comma delimited string from a cluster without utilizing 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
Clarification:
We use for the circle to peruse the cluster and store it into a string delimited by a (,) at whatever point one value in the exhibit is printed. This proceeds until we arrive at the last string to abstain from printing another comma toward the finish of the rundown.