Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop, but for first key do something else

Tags:

foreach

php

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?

like image 336
Benny Avatar asked Nov 28 '22 12:11

Benny


1 Answers

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']);
like image 173
John Kugelman Avatar answered Dec 09 '22 14:12

John Kugelman