Alan
Alan

Reputation: 213

Stop the comma separation at the last result

I have an array stored in a variable called $data that looks like this:

["data"]=>
    ["rows"]=>
    array(30) {
      [0]=>
      array(2) {
        [0]=>
        string(10) "2016-08-15"
        [1]=>
        int(3)
      }
      [1]=>
      array(2) {
        [0]=>
        string(10) "2016-08-16"
        [1]=>
        int(18)
      }
      [2]=>
      array(2) {
        [0]=>
        string(10) "2016-08-17"
        [1]=>
        int(5)
      }
      [3]=>
      array(2) {
        [0]=>
        string(10) "2016-08-18"
        [1]=>
        int(3)
      }
      [4]=>
      array(2) {
        [0]=>
        string(10) "2016-08-19"
        [1]=>
        int(11)
      }
      [5]=>
      array(2) {
        [0]=>
        string(10) "2016-08-20"
        [1]=>
        int(5)
      }

And I try to take the values from 30 entries and add a comma and a space:

                    <?php
                    foreach ($data->data->rows as $data) {
                        if (isset($data[1])) {
                            echo $data[1] . ', ';
                        }
                    }
                    ?>

The result looks like this:

[18, 5, 3, 11, 5, 7, 9, 7, 17, 6, 3, 3, 1, 19, 13, 7, 3, 4, 10, 3, 5, 5, 7, 4, 2, 1, 8, 10, 6, 9, ],

But after the last entry I don't want to have a comma and the space. How can I do this?

Upvotes: 1

Views: 66

Answers (4)

JasonD
JasonD

Reputation: 114

You can also try this low-tech solution:

<?php
    $sep = "";
    foreach ($data->data->rows as $data) {
        if (isset($data[1])) {
            echo $sep . $data[1];
            $sep = ', ';
        }
    }
?>

Basically what you are doing is setting the delimiter in front of the string. It's empty at first, so there will be no delimiter, but after the first iteration it will be populated, putting the delimiter in front of all future strings. Also, because it is in the beginning, there is nothing to trail after the last one.

Perhaps not the best solution, but certainly easy and understandable.

Upvotes: 0

PHP Geek
PHP Geek

Reputation: 4033

Yes you can use it using implode as well as you own logic..
<?php
 foreach ($data->data->rows as $key => $data) {
  if (isset($data[1])) {
    echo $data[1];
    if($key === count($data->data->rows) -1){
      echo ' , ';
    }
  }
 }
?>

Upvotes: 0

Dmytrechko
Dmytrechko

Reputation: 598

Just use implode and array_column:

$prepared_array = array_column($data, 1);

$result = array_implode(', ',$prepared_array);

Upvotes: 5

u_mulder
u_mulder

Reputation: 54841

I advise you this solution:

$values = [];
foreach ($data->data->rows as $data) {
    if (isset($data[1])) {
        $values[] = $data[1];
    }
}
echo implode(',', $values);

Also if you're trying to get json string - better use json_encode:

echo json_encode($values);

Upvotes: 5

Related Questions