Keverw
Keverw

Reputation: 3786

extra space being added in array output

I'm trying to create a custom function 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

Upvotes: 0

Views: 199

Answers (3)

Momen Zalabany
Momen Zalabany

Reputation: 9007

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

Upvotes: 0

dvir
dvir

Reputation: 5115

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

Upvotes: 1

KilZone
KilZone

Reputation: 1615

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).

Upvotes: 4

Related Questions