Stack Stack - 6 months ago 9
PHP Question

How to make a string from one kind of array items?

I have an array like this:

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
Array
(
[0] => Array
(
[id] => 191
[type] => 3
[table_code] => 15
)

[1] => Array
(
[id] => 192
[type] => 3
[table_code] => 15
)

[2] => Array
(
[id] => 194
[type] => 3
[table_code] => 15
)
)
*/


And I'm trying to make a string of all IDs with a comma separator. Something like this:

echo $ExpectedOutput; // 193, 192, 194


How can I do that?




Here is what I've tried so far:

foreach($results as $item) {
$ExpectedOutput = $item['id'];
}


But always there is a
,
in the end of that string.

Answer

You can do this using the implode and array_column.

Array Column makes an array from all the id of that array, and after that implode makes a string from that array with a delimiter. As you want to use ,.

echo implode(", ", array_column($results, "id")); //193, 192, 194