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

Fly*_*Cat 0 php

我试图通过使用foreach循环找到数组中的最后一个元素.

我有..

  foreach ( $employees as $employee ) {

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

  }
Run Code Online (Sandbox Code Playgroud)

我不想在最后一名员工中添加'和'.反正有没有这样做?非常感谢!

rai*_*7ow 6

我想还有另一种方式:

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

这很简单:array_map将创建一个$employee->name元素数组,而implode将使用' and 'string作为'glue' 来创建一个字符串.)