Jump to content

Classic Kill Last Comma In Loop


chasethemetal

Recommended Posts

Hey all!So I need to kill the last comma in this simple loop.It looks like: LatLng(40.713, -73.946), LatLng(40.713, -73.946), but needs to looks likeLatLng(40.713, -73.946), LatLng(40.713, -73.946)The comma is outside the variable $location which might make this more difficult. My code breaks if that last comma is inputed. I am inputing values inside of a javascript function.<?php $data = mysql_query("SELECT * FROM location ORDER BY id ASC LIMIT 2") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { $latitude = $info['latitude']; $longitude = $info['longitude']; $location = $latitude .", ". $longitude; echo 'LatLng('.$location.'), ';} ?>Any help would be great thanks so much!

Link to comment
Share on other sites

you can use strrpos() to get the last occurance of the character. and then you can use substr() to extract the partial string

Link to comment
Share on other sites

Or what I prefer to do in situations like this is to save your output to a string first. Then you can check if it's empty, and if it's not, add your comma. So something like this:

$str = ''; //Initialize it to an empty stringwhile ($info = mysql_fetch_array( $data )) {      ....      //Check if the string already has text in it, and if so, add a comma   if ($str != '') {	  $str.=', ';   }      //Add the data to the string   $str.='LatLng('.$location.')';}//Now output the stringecho $str;

Link to comment
Share on other sites

Preg_Replace Is One Of The Good Method For That.If You Are Using While? Then First Add Comma Then Set ValuesSo In The End Your Output Will Look Like This: , abc, def, ghiThen in the end just use preg_replace();e.g:$result = ', abc, def, ghi';print preg_replace('/, /', '', $result, 1);This will replace just one first comma. Because we used value 1 in the end of preg_replace() command.Hope u understand.This will help in future :)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...