4

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?

1
  • 1
    Note that you're not validating the input in anyway. This can lead to injection vulnerabilities. Commented Jul 21, 2010 at 0:22

5 Answers 5

22

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']); 
Sign up to request clarification or add additional context in comments.

1 Comment

$_POST['technologies'] might not have numeric keys
5

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

Comments

1

You need some kind of a flag:

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

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.