Skip to content

Instantly share code, notes, and snippets.

@ckoulatsi
Last active January 2, 2023 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckoulatsi/756c84cc2ebe920b5265974c77c3a307 to your computer and use it in GitHub Desktop.
Save ckoulatsi/756c84cc2ebe920b5265974c77c3a307 to your computer and use it in GitHub Desktop.
[PHP] Useful snippets #functions #classes

array_filter (with a custom filter example)

<?php 
    $items = [
        [
            'author' => 'Stephen King',
            'title' => 'The Thing',
            'year' => 1979
        ],
        [
            'author' => 'Dean Koonz',
            'title' => 'The Twins',
            'year' => 1998
        ],
        [
            'author' => 'J.R.R. Tolkien',
            'title' => 'Lord of the Rings',
            'year' => 1926
        ],
        [
            'author' => 'J.R.R. Tolkien',
            'title' => 'The Hobbit: Desolation of Smaug',
            'year' => 1936
        ]
    ];

    // custom fulter function very similar to the php build in function array_filter
    // $filter = function($items, $fn) {
        
    //     $filteredItems = [];

    //     foreach($items as $item) {
    //         if($fn($item)) {
    //             $filteredItems[] = $item;
    //         }
    //     }
    //     return $filteredItems;
    // };

    $filteredBooks = array_filter($items, function($book) {
        return $book['year'] >= 1936 && $book['year']<= 1979;
    });
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lamda Functions</title>
    <style>
        body {
            font-family: sans-serif;
            font-size: 18px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
    <h1>Lamda functions</h1>
    <ul>
        <?php foreach($filteredBooks as $book) : ?>
            <li><?= "{$book['year']} - {$book['title']} by author: {$book['author']}" ?></li>
        <?php endforeach ?>
    </ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment