2012-10-16 44 views
0

我想通过使用foreach循环找到数组中的最后一个元素。如何找到数组的最后一个元素

我..

foreach ($employees as $employee) { 

     $html.=$employee ->name.'and '; 

    } 

我不希望添加“和”最后的雇员。有没有办法做到这一点?非常感谢!

回答

6

还有另外一种方式,我想:

$html = implode(' and ', 
    array_map(function($el) { return $el->name; }, $employees)); 

很简单:array_map将创建$employee->name元素的数组,并implode将一个字符串从这些使用' and '字符串作为“胶水”。 )

2

比在你的foreach中有一个计数器更清洁的方法可能是简单地删除字符串的最终“和”。

foreach ($employees as $employee) { 
    $html .= $employee->name . 'and '; 
} 
$html = substr($html, 0, strlen($html) - 4); 
相关问题