I'm having a bit of trouble with an annoying ',' during the iteration of a PHP array to produce a Javascript array. Essentially, what I have is this:
<?php
$array = array(StdObject,StdObject,StdObject);
?>
//later that page...in JavaScript
var list = [
<?php foreach($array as $value):?>
'<?=$value->some_letter_field?>',
<?endforeach;?>
];
Unfortunatly, what this code does is produce output that looks like this:
var list = ['a','b','c',];
Notice that extra ma in the JavaScript array? This is causing some issues. How would I go about re-writing this PHP snippet so that extra ma doesn't get printed, producing a properly formatted JavaScript array?
The expected output should be:
var list = ['a','b','c'];
I appreciate your help in advance.
I'm having a bit of trouble with an annoying ',' during the iteration of a PHP array to produce a Javascript array. Essentially, what I have is this:
<?php
$array = array(StdObject,StdObject,StdObject);
?>
//later that page...in JavaScript
var list = [
<?php foreach($array as $value):?>
'<?=$value->some_letter_field?>',
<?endforeach;?>
];
Unfortunatly, what this code does is produce output that looks like this:
var list = ['a','b','c',];
Notice that extra ma in the JavaScript array? This is causing some issues. How would I go about re-writing this PHP snippet so that extra ma doesn't get printed, producing a properly formatted JavaScript array?
The expected output should be:
var list = ['a','b','c'];
I appreciate your help in advance.
Share Improve this question edited Dec 11, 2012 at 16:46 Sami 7239 silver badges25 bronze badges asked Dec 11, 2012 at 16:36 SinmokSinmok 6561 gold badge11 silver badges20 bronze badges6 Answers
Reset to default 9You don't need to do this yourself, PHP has a function called json_encode
that does what you want. If for some reason you don't have PHP 5.2.0, there are a lot of implementations in the ments of that page to get around that.
Use implode() to glue up array elements. It will take care about mas
//later that page..in JavaScript
var list = ['<?=implode("', '", $array)?>'];
You can use this to generate the json array:
$list = json_encode($array);
And then read it in Javascript:
var list = <?=$list?>
This will do the trick:
<?php
$filtered = array();
foreach($array as $value) {
$filtered[] = $value->some_letter_field;
}
echo 'var list = ' . json_encode($filtered);
?>
How about converting array to a valid JSON object?
var list = JSON.parse("<?php echo json_encode($array); ?>");
Anyway, do you really need to generate JS code on the fly? Isn't there another way to plete your task? JS generation is often considered a hack, and it can be avoided easily in many cases.
If you insist in keeping your current code for whatever reason, just:
var list = [
<?php foreach($array as $value): ?>
$output[] = "'".$value->some_letter_field."'";
<?php endforeach; ?>
echo implode(',', $output);
];