You can use the trim to remove the last character on the right, the second argument says which one should be the character.
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
substr
Or with substr, which will remove 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 you can use anonymous functions, which combined with array_map () removes the foreach. array_map
applies a function to all elements of an array ( $row
), the anonymous function only returns the ID
property of the object, then just use the implode () to convert the array to a comma-separated string, as demonstrated by Jefferson Silva.
This approach was taken from PHP - Extracting 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