Alan Alan - 2 months ago 6
PHP Question

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?

Answer

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);
Comments