1cd9c8984f2fdeb996130d54d62a98d9

Hi guys,
Is there other way to improve this code below?
Thanks : )

<?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 !

D41d8cd98f00b204e9800998ecf8427e

bob

January 23, 2009, January 23, 2009 04:17, permalink

7 ratings. Login to rate!

Even gets rid of the trailing comma

implode(",", $arr)
D41d8cd98f00b204e9800998ecf8427e

john

January 23, 2009, January 23, 2009 05:01, permalink

3 ratings. Login to rate!

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;
}
23132e1aa8457e11b243a43b578d51dc

Simo Niemelä

January 25, 2009, January 25, 2009 15:16, permalink

2 ratings. Login to rate!
<?php

function array_to_list($array, $separator = ',')
{
  return join($separator, $array);
}
8bba46dba9043c254e6eef1aa664e6f0

ellisgl.myopenid.com

February 11, 2009, February 11, 2009 18:11, permalink

No rating. Login to rate!

implode is the best way..

9be98dfa0cab54033aebb909a5d1df84

hlegius

September 30, 2009, September 30, 2009 18:13, permalink

No rating. Login to rate!

@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);

?>

Your refactoring





Format Copy from initial code

or Cancel