Skip to content
This repository has been archived by the owner on Jun 17, 2021. It is now read-only.

Latest commit

 

History

History
24 lines (19 loc) · 465 Bytes

findLast.md

File metadata and controls

24 lines (19 loc) · 465 Bytes
title tags
findLast
array,beginner

Returns the last element for which the provided function returns a truthy value.

  • Use array_filter() to remove elements for which $func returns falsy values, array_pop() to get the last one.
function findLast($items, $func)
{
  $filteredItems = array_filter($items, $func);

  return array_pop($filteredItems);
}
findLast([1, 2, 3, 4], function ($n) {
  return ($n % 2) === 1;
});
// 3