Comma Iteration

From Superk

Jump to: navigation, search

Simple function for iterating over an array and outputting the contents seperated by commas:

$workday = array('Mon', 'Tues', 'Wed', 'Thurs', 'Fri');

function addCommas($input) {
  $out = '';

  for($w=0;$w<count($input);$w++) {  
    if($w < count($input)-1) { 
      $out .= $input[$w].', '; 
    } else { 
      $out .= $input[$w]; 
    }
  }

  return $out;
}

echo addCommas($workday);

Will output:

Mon, Tues, Wed, Thurs, Fri
NOTE: No comma on the end.

I'm Not So Bright

Of course if I had half a brain, I'd just use the built-in function join():

$workday = array('Mon', 'Tues', 'Wed', 'Thurs', 'Fri');

echo join(",", $workday);
Personal tools