Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a javascript array in php with "Foreach" Loop

So I'm generating a javascript array of objects in php with a for loop. My code looks somewhat like this:

<script type="text/javascript">

var items = [ 
<?php foreach($items as $item): ?>
     {
        "title" : "<?php echo $item->title ?>",
        "image" : "<?php echo $item->getImage()?>",
      }, 
 <?php  endforeach ?>
];

</script>

This code will not work, since I end up with an extra comma at the end of my javascript array. Is there an elegant way to deal with that comma that separates the javascript objects?

like image 225
CamelBlues Avatar asked Aug 30 '26 02:08

CamelBlues


1 Answers

You should use json_encode().

<?php
    $jsItems = array();
    foreach($items as $item) {
        $jsItems[] = array(
            'title' => $item->title,
            'image' => $item->getImage()
        );
    }
    echo 'var items = '.json_encode($jsItems).';';
?>
like image 85
ThiefMaster Avatar answered Aug 31 '26 14:08

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!