tags:

views:

91

answers:

3

Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.

I'm using the following foreach loop:

foreach ($_POST['technologies'] as $technologies){
    echo ", " . $technologies;
}

Which produces:

, First, Second, Third

What I want:

First, Second, Third

All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?

+9  A: 

You can pull out the indices of each array item using => and not print a comma for the first item:

foreach ($_POST['technologies'] as $i => $technologies) {
    if ($i > 0) {
        echo ", ";
    }

    echo $technologies;
}

Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":

echo implode(", ", $_POST['technologies']);
John Kugelman
+1 for implode()
scunliffe
+1 for implode()
George Marian
+1 Yes, the implode is nice
derekerdmann
$_POST['technologies'] might not have numeric keys
Kamil Szot
Ah, implode() works perfect. Thanks!
Benny
+2  A: 

For general case of doing something in every but first iteration of foreach loop:

$first = true;
foreach ($_POST['technologies'] as $technologies){
    if(!$first) {
      echo ", ";
    } else {
      $first = false;
    }
    echo $technologies;
}

but implode() is best way to deal with this specific problem of yours:

echo implode(", ", $_POST['technologies']);
Kamil Szot
+1  A: 

You need some kind of a flag:

$i = 1;
foreach ($_POST['technologies'] as $technologies){
  if($i > 1){
    echo ", " . $technologies;
  } else {
    echo $technologies;
  }
  $i++;
}
scubacoder