user1105787
user1105787

Reputation:

remove all but last comma

i have the following code:

while (list($key, $value) = each($arr)) {

    $implode_keys_values = @"$key=$value,";



    echo"$implode_keys_values";
}

which ends up echoing out xxxx=xxxx,xxxx=xxxx,xxxx=xxxx,xxxx=xxxx, depending on how many keys/values there are.

how do I take this dynamically changing string and remove the very last comma on it?

keep in mind:

$implode_keys_values = substr($implode_keys_values,0,-1);

will not work, it will take out all the commas.

Upvotes: 1

Views: 201

Answers (3)

GBD
GBD

Reputation: 15981

In your case, this would be a better way to implement implode():

$data = array();
while (list($key, $value) = each($arr)) {
   $data[] = "$key=$value";
}
echo implode(",",$data);

Upvotes: 0

hakre
hakre

Reputation: 197795

PHP has a function built in for that if the data in the array is not too complex (works for the xxxxxx values you have, can break with others):

echo http_build_query($arr, '', ',');

See http_build_query().

Another alternative is using iterators and checking if the current iteration is the last one. The CachingIterator::hasNext() method is helpful for that:

$it = new CachingIterator(new ArrayIterator($arr));
foreach($it as $key => $value) {
    echo $key, '=', $value, $it->hasNext() ? ',' : '';
}

This variant does work with any data.

Upvotes: 2

Laurence
Laurence

Reputation: 60048

rtrim($implode_keys_values, ",") would cut trailing commas.

You can learn more about rtrim here at the PHP docs

$implode_keys_values = "";
while (list($key, $value) = each($arr)) {

    $implode_keys_values .= @"$key=$value,";
}
echo rtrim($implode_keys_values, ",");

Upvotes: 3

Related Questions