0

I am not sure if I need to determine the last loop or if there is a better way to do this. But I am trying to generate a list of items within square brackets and the last item can't have a comma.

Here is my code:

content_ids: ["<?php  for ($i=0, $n=sizeof($products_array); $i<$n; $i++) {echo $products_array[$i]['id'].',';} ?>"]

So this would print:

content_ids: ["1,2,3,"]

The last comma after 3 should not be there.

Sackling
  • 1,780
  • 5
  • 37
  • 71

2 Answers2

4

What about trying this

content_ids: ["<?php

for ($i=0, $n=sizeof($products_array); $i<$n; $i++) {

    if($i == ($n-1)){
        echo $products_array[$i]['id']; 
    }else{
        echo $products_array[$i]['id'].','; 
    };

};

?>"]
Dieskim
  • 600
  • 3
  • 12
  • I think this will work however there are other items in the array and I only want the "id" I tried this but it does not work with implode because it is a single value: for ($i=0, $n=sizeof($products_array); $i<$n; $i++) { echo implode( ",", $products_array[$i]['id'] ); } – Sackling Oct 24 '17 at 01:46
  • ok I edited the above code - you just need to check for the last item as `$i == ($n-1)` – Dieskim Oct 24 '17 at 01:57
  • Ya this works perfect. I do feel like I should have been able to do it with implode like you originally thought. But this will work:) – Sackling Oct 24 '17 at 02:03
  • To use Implode you would need to array_pop the last item off, implode and then add it back on - see this https://stackoverflow.com/questions/8586141/implode-array-with-and-add-and-before-last-item – Dieskim Oct 24 '17 at 02:12
1

You can use array_column() to accomplish this in one single line:

$products_array = array(
  array(
    'id' => 1,
  ),
  array(
    'id' => 2,
  ),
  array(
    'id' => 3,
  ),
);
echo '["'.implode(',',array_column($products_array, 'id')).'"]';
// Displays ["1,2,3"]
Mike
  • 23,542
  • 14
  • 76
  • 87