字符串逗号分隔成字符串数组_PHP | 从数组创建逗号分隔的字符串,而无需使用库函数

字符串逗号分隔成字符串数组

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代码无需使用库函数即可从数组创建逗号分隔的字符串 (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.

每当打印数组中的一个值时,我们使用for循环读取数组并将其存储到以( , )分隔的字符串中。 这一直持续到我们到达最后一个字符串为止,以避免在列表末尾打印另一个逗号。

翻译自: https://www.includehelp.com/php/create-comma-delimited-string-from-an-array-without-using-library-function.aspx

字符串逗号分隔成字符串数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值