0

I am trying to find the last element in the array by using foreach loop.

I have..

  foreach ( $employees as $employee ) {

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

  }

I don't want to add 'and' to the last employee. Are there anyways to do this? Thanks a lot!

2 Answers 2

6

There's another way, I suppose:

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

It's simple: array_map will create an array of $employee->name elements, and implode will make a string from these, using ' and ' string as 'glue'. )

Sign up to request clarification or add additional context in comments.

Comments

1

A cleaner approach than having a counter in your foreach could be to simply remove the final "and " off of your string.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.