a79ce734e1
a79ce734e1

Reputation: 875

Foreach loop, but for first key do something else

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?

Upvotes: 4

Views: 10355

Answers (5)

Nabeel Khan
Nabeel Khan

Reputation: 3993

Why don't you simply use PHP builtin function implode() to do this more easily and with less code?

Like this:

<?php
$a = ["first","second","third"];
echo implode($a, ", ");

So as per your case, simply do this:

echo implode($_POST['technologies'], ", ");

Upvotes: 0

treyBake
treyBake

Reputation: 6560

Adding an answer that deals with all types of arrays using whatever the first key of the array is:

# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array)); 

foreach ($array as $key => $value)
{
    # if current $key !== $firstKey, prepend the ,
    echo ($key !== $firstKey ? ', ' : ''). $value;
}

demo

Upvotes: 1

scubacoder
scubacoder

Reputation: 105

You need some kind of a flag:

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

Upvotes: 1

Kamil Szot
Kamil Szot

Reputation: 17817

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']);

Upvotes: 5

John Kugelman
John Kugelman

Reputation: 361595

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']);

Upvotes: 22

Related Questions