0

I need help in how to remove the last comma from this looped var, please.

$image_meta .= "{\"id\":\"".$img_id."\",\"client\":\"".$img_desc."\",\"desc\":\"Test\"},";

FireFox doesn't seem to mind it, but IE does.

If there is any way to even get rid of the .= and loop my data in another way, i would be most thankful.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Khaled
  • 154
  • 2
  • 8

3 Answers3

3

We would need to see the rest of the script. But from what I understand of your situation, when you echo $image_meta (after the loop I suppose) you could do one of the two:

echo rtrim($image_meta,',');

or

echo substr($image_meta,0,-1);
alex
  • 131
  • 1
  • 5
0

look at implode:

http://php.net/manual/en/function.implode.php

Just to clarify, I'm guessing your doing something similar to this:

$image_meta = '';
foreach($blahs as $blah){
   $image_meta .= "{\"id\":\"".$img_id."\",\"client\":\"".$img_desc."\",\"desc\":\"Test\"},";
}

Something like this should work:

$image_meta_arr = array();
foreach($blahs as $blah){
   array_push($image_meta, "{\"id\":\"".$img_id."\",\"client\":\"".$img_desc."\",\"desc\":\"Test\"}";
}

$image_meta = implode(',', $image_meta_arr);
MarkR
  • 187
  • 1
  • 9
  • I checked the whole implode function, but failed at using it with just that 1 line, any idea how can implant it? – Khaled Feb 20 '12 at 18:33
0

You can do like this:

$ar_image_meta = array();

for/foreach() // your loop
{
  $ar_image_meta[] = '{"id":"'.$img_id.'","client":"'.$img_desc.'","desc":"Test"}';
}

$image_meta = implode(", ", $ar_image_meta);

If your goal is to "convert" a PHP variable to a Javascript one, have a look at json_encode().

Maxime Pacary
  • 22,336
  • 11
  • 85
  • 113