Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


>Solution :

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;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading