Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a foreach loop, but do something different on the last iteration?

Tags:

php

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?

I have an array of names. I want to output the list of names separated by commas.

Joe, Bob, Foobar

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!).

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

$users = array();
$users[] = new User();

foreach ($users as $user) {
    echo $user->name;
    echo ', ';
}

How can I achieve this and still use these objects?

Update: 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:

$array = array();
foreach($users as $user) {
    $array[] = $user->name;
}
$names = implode(', ', $array);
like image 593
Andrew Avatar asked Dec 03 '09 01:12

Andrew


3 Answers

Use implode:

$names = array('Joe', 'Bob', 'Foobar');
echo implode(', ', $names); # prints: Joe, Bob, Foobar

To clarify, if there is only one object in the array, the ', ' separator will not be used at all, and a string containing the single item would be returned.

EDIT: If you have an array of objects, and you wanted to do it in a way other than a for loop with tests, you could do this:

function get_name($u){ return $u->name; };
echo implode(', ', array_map('get_name', $users) ); # prints: Joe, Bob, Foobar
like image 63
Doug Neiner Avatar answered Nov 10 '22 10:11

Doug Neiner


$array = array('joe', 'bob', 'Foobar');
$comma_separated = join(",", $array);

output:

joe,bob,Foobar

like image 32
µBio Avatar answered Nov 10 '22 08:11

µBio


Sometimes you might not want to use implode. The trick then is to use an auxiliary variable to monitor not the last, but the first time through the loop. vis:

$names = array('Joe', 'Bob', 'Foobar');
$first = true;
$result = '';
foreach ($names as $name)
{
   if (!$first)
      $result .= ', ';
   else
      $first = false;

   $result .= $name;
}
like image 38
dar7yl Avatar answered Nov 10 '22 10:11

dar7yl