How to use a foreach loop, but do something different on the last iteration?
<p>This is probably a simple question, but how do you iterate through an array, doing something to each one, until the last one and do something different?</p>

<p>I have an array of names. I want to output the list of names separated by commas.</p>

<blockquote>
  <p>Joe, Bob, Foobar</p>
</blockquote>

<p>I don't want a comma at the end of the last name in the array, nor if there is only one value in the array (or none!).</p>

<p><strong>Update:</strong> I can't use <code>implode()</code> because I have an array of User model objects where I get the name from each object.</p>

<pre><code>$users = array();
$users[] = new User();

foreach ($users as $user) {
    echo $user-&gt;name;
    echo ', ';
}
</code></pre>

<p>How can I achieve this and still use these objects?</p>

<p><strong>Update:</strong> I was worrying too much about how many lines of code I was putting in my view script, so I decided to create a view helper instead. Here's what I ended up with:</p>

<pre><code>$array = array();
foreach($users as $user) {
    $array[] = $user-&gt;name;
}
$names = implode(', ', $array);
</code></pre>
