<?php
/*
Return a string representation of an array [1,2,3] of the form "1,2,3"
*/
function array_to_list ($arr)
{
$ret = "";
$n=count($arr)
for( $i = 0; $i < $n; $i ++) {
$ret .= $arr[$i];
$ret .= ",";
}
return $ret;
}
Refactorings
No refactoring yet !
bob
January 23, 2009, January 23, 2009 04:17, permalink
Even gets rid of the trailing comma
implode(",", $arr)
john
January 23, 2009, January 23, 2009 05:01, permalink
If you wanted it to look more like your code, you would probably do something like this:
<?php
/*
Return a string representation of an array [1,2,3] of the form "1,2,3"
*/
function array_to_list ($arr)
{
$ret = "";
foreach ($arr as $x) {
$ret .= "$x,";
}
return $ret;
}
Simo Niemelä
January 25, 2009, January 25, 2009 15:16, permalink
<?php
function array_to_list($array, $separator = ',')
{
return join($separator, $array);
}
ellisgl.myopenid.com
February 11, 2009, February 11, 2009 18:11, permalink
implode is the best way..
hlegius
September 30, 2009, September 30, 2009 18:13, permalink
@Simo Niemelä
Do not create a function for abstract another native alternative. Is less readable. And do not forget: alias (join is one of them) will be killed at PHP 6.
Use implode instead.
<?php
$str_fromArray = implode(",", $arr);
?>
Hi guys,
Is there other way to improve this code below?
Thanks : )