开发者

extra space being added in array output

I'm trying to create a custom f开发者_如何学编程unction to take a array and add comma. Like for a location or list of items.

function arraylist($params)
{
    $paramlist = reset($params);
    while($item = next($params))
    {
        $paramlist = $item . ', ' . $paramlist;
    }
    return $paramlist;
}

$location = array('San Francisco','California','United States');

echo arraylist($location);

San Francisco , California, United States is the output. It should out put San Francisco, California, United States


This is a duplicate of the function implode already present in PHP, is there a reason you do this by hand?

echo implode(', ', array('San Francisco','California','United States'));

The above does the same as your arraylist-function.

Small update: I noticed you append your 'next item' to the beginning of your string ($item . ', ' . $paramlist), which will inverse your array order. The output will be (United States, California, San Francisco). If this is on purpose, please use array_reverse to achieve the same ordering (together with implode).


You can instead just use implode(", ", $location).


There is already and existent function for doing this, called implode.

echo implode(',',$array);

that will covert the array into a string with a , in between , u can change ',' into any thing you want :)/

hope it helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜