Possible Duplicate:
comma separated list in php
Problem:
I want to be able to iterate through a list of unknown size, and spit out a comma delimited list.
For example:
Input:
$data = array();
$data[0]['productId'] = 11;
$data[1]['productId'] = 22;
$data[2]['productId'] = 33;
$data[3]['productId'] = 44;
The following code does the trick:
$prodsToCheck = "";
foreach ($data as $d) {
$prodsToCheck .= $d['productId'].", ";
}
$prodsToCheck = substr($prodsToCheck, 0, strlen($prodsToCheck) - 2); // THIS IS THE IMPORTANT PART
print $prodsToCheck; die();
Result must be
11, 22, 33, 44
and NOT:
11, 22, 33, 44,
This can’t be the quickest way to do this… what is?
Your example and your code are incoherent, so I decided to ignore the example since the problem would be too simple otherwise.
You may use implode, array_map and an anonymous function like this:
Completely untested and supposed to work with php 5.3+