Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions Introducing Functions PHP Function Arguments

6,116 Points

inserting a word at specific place place in for each loop

do i know how to use array to write "hello paul , david , lisa" but what if it want to insert a word in between like write " hello paul , david and lise"

1 Answer

Sharina Jones
Sharina Jones
2,223 Points

I guess I have to post this as an answer?

You'd have to check the length of the array, then insert conditional code that inserts 'and' before the end of the array is reached.


$names = array('paul', 'david', 'lisa');
$arr_length = count($names); //gets the length of the array
$c = 0; //counter

echo "<p>Hello ";
foreach($names as $name) {
  if ($c == ($arr_length - 1)) {
    echo " and ";
  echo "$name ";

echo "</p>";