In this example, we will show you how to build an universal filtering function to sort your list items in PHP, using the Lambda, or anonymous function.
<!DOCTYPE html>
<html>
<head>
<title>
Lambda Filter Example
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>List of Items</h1>
<?php
// Our source of items, in this case an Associative Array
$albums = [
[
'name' => 'Voices',
'artist' => 'Vangelis',
'year' => 1995
],
[
'name' => 'Pure Instinct',
'artist' => 'Scorpions',
'year' => 1996
],
[
'name' => 'Tranceport',
'artist' => 'Paul Oakenfold',
'year' => 1998
]
];
// Here we filter our list of albums, using PHP native function array_filter()
// and the Lambda, or anonymous function.
// The resulting array will contain items filtered according to our criteria.
$filteredAlbums = array_filter($albums, function ($album) {
return $album['year'] < 1998;
//return $album['artist'] === 'Vangelis';
//return str_starts_with($album['name'], 'Pure');
});
?>
<!-- Display the list of filtered items-->
<ul>
<?php foreach ($filteredAlbums as $album): ?>
<li>
<?php
echo $album['name'] . " - " . $album['name'] . " (" . $album['year'] . ")";
?>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>