Jump to content

Remove the last comma


Endorphin
 Share

Recommended Posts

Hi All,

I'm sure there is an easy solution for this but I am unable to find it.

I am new to PHP and after a little help...

 

the via data is stored in a database in this format... |51.105166,-1.695971|51.011055,-2.1068|50.945233,-2.617664||||

 

I'm trying to find a way of loosing the last comma if there are 1 or more entries, any ideas guys.

 

 

 

What I'm getting is :

var points = [{location: '51.105166,-1.695971'},{location: '51.105166,-1.695971'},];

 

What I'm after is:

var points = [{location: '51.105166,-1.695971'},{location: '51.105166,-1.695971'}];

 

 

<?php
if($via != null){
echo "var points = [";
foreach($via as $point){
if($point != ""){
echo "{location:";
echo " '".$point."'";
echo "},";
}	
}
echo "];\n";
}
?>

Link to comment
Share on other sites

You'd better do it in another way. The more accurate (and more compact) code is the next

if($via != null)
{
$points=array();
foreach($via as $point)
{
if($point != "")
  $points[]="{location:'$point'}";
}
if( count( $points > 0 ) )	
  echo "var points = [".implode( ',', $points)."];\n";

Link to comment
Share on other sites

I have a question for you. If you also believe that it should be done another way, and I'm sure you've seen that OP is trying to learn that better way, why did you give him/her the bad answer?

What is wrong in my answer? Endorphin tries to create a list of comma-separated values. His task was to remove the last comma. Am I right? And I show the way how to create a string without comma at it's end. Do you agree? OK, again - where my answer is wrong?

 

Even if he would like to use multidimensional array, he can use my code. He just need to change it a little.

Link to comment
Share on other sites

Your answer is right, it's the best way to build a string like that without having a trailing comma that needs to be removed. I'm just saying that using something like json_encode(), which is for situations exactly like this one, is better.

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.