Skip to content

Instantly share code, notes, and snippets.

@ilmoralito
Last active March 29, 2024 15:00
Show Gist options
  • Save ilmoralito/4bba321fbea70be2a78d226f602a322c to your computer and use it in GitHub Desktop.
Save ilmoralito/4bba321fbea70be2a78d226f602a322c to your computer and use it in GitHub Desktop.
Simple PHP lambda example
<?php
$books = [
[
'name' => 'Earth 1',
'author' => 'Andrew',
'pubDate' => '2024-03-08'
],
[
'name' => 'Earth 3',
'author' => 'Andrew',
'pubDate' => '2023-02-18'
],
[
'name' => 'Lorem',
'author' => 'Andy',
'pubDate' => '2021-03-18'
]
];
function filter($items, $fn) {
$filteredItems = [];
foreach ($items as $item) {
if ($fn($item)) {
$filteredItems[] = $item;
}
}
return $filteredItems;
}
$output = filter($books, function ($book) {
return $book['author'] === 'Andrew';
});
print_r($output);
/*
Array
(
[0] => Array
(
[name] => Earth 1
[author] => Andrew
[pubDate] => 2024-03-08
)
[1] => Array
(
[name] => Earth 3
[author] => Andrew
[pubDate] => 2023-02-18
)
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment