0

I would like to simply filter my array:

$products = array(
  (object) [
    'createdAt' => "2021-12-29T14:11:47.000000Z",
    'id' => 11
  ],
  (object) [
    'createdAt' => "2021-12-29T14:11:47.000000Z",
    'id' => 22
   ],
   (object) [
     'createdAt' => "2021-12-30T09:50:42.000000Z",
     'id' => 11
   ]
);

$fun = array_filter($products, function($item){
    return $item->createdAt == end($products)->createdAt;
});

print_r($fun);

Why I am getting error? I can't use end inside array filter?

Error: Uncaught TypeError: end(): Argument #1 ($array) must be of type array, null given


LiOne
  • 17
  • 1
  • 5

1 Answers1

1

You don't have access to that outer variable $products within your anonymous function. Make it accessible by adding use ($products) in the following way:

$fun = array_filter($products, function($item) use ($products) {
    return $item->createdAt == end($products)->createdAt;
});
Nico Haase
  • 11,420
  • 35
  • 43
  • 69