Php 如何查找数组的最后一个元素

Php 如何查找数组的最后一个元素,php,Php,我试图使用foreach循环查找数组中的最后一个元素 我有 foreach ( $employees as $employee ) { $html.=$employee ->name.'and '; } 我不想在最后一名员工中添加“和”。有办法做到这一点吗?非常感谢 我想还有另一种方法: $html = implode(' and ', array_map(function($el) { return $el->name; }, $employe

我试图使用foreach循环查找数组中的最后一个元素

我有

  foreach ( $employees as $employee ) {

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

  }

我不想在最后一名员工中添加“和”。有办法做到这一点吗?非常感谢

我想还有另一种方法:

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

它很简单:将创建一个
$employee->name
元素数组,并使用
'和'
字符串作为'glue'从这些元素生成一个字符串。)

一种比在foreach中使用计数器更干净的方法是简单地删除字符串中的final“and”

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