You can use the Trim to remove the last character right, the second argument says which character should be.
Trim
<?php
$rows = array("125", "148", "157", "169", "185");
$all_ids = "";
foreach ($rows as $item){
$all_ids .= $item.", ";
}
echo trim(trim($all_ids),',');
Example - ideone
replace
Or with substr, which will remove the space and comma.
<?php
$rows = array("125", "148", "157", "169", "185");
$all_ids = "";
foreach ($rows as $item){
$all_ids .= $item.", ";
}
$all_ids = substr($all_ids, -0, -2);
echo $all_ids;
Example - ideone
array_map
From php5.3 it is possible to use anonymous functions, which combined with array_map() eliminates the foreach. array_map
apply a function to all elements of an array($row
), anonymous function only returns property ID
of the object, then just use the implode() to convert the array into a comma-separated string, as demonstrated by Jefferson Silva.
This approach was taken from PHP - Extracting a Property from an array of Objects
<?php
//Monta um array igual ao da pergunta
$valores = array("125", "148", "157", "169", "185");
for($i=0; $i<5; $i++){
$obj = new stdClass();
$obj->ID = $valores[$i];
$rows[] = $obj;
}
$all_ids = array_map(function($item){ return $item->ID; }, $rows);
echo implode(',', $all_ids);
Example - ideone
obviously the best option for the question posed.
– chambelix