Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Created September 29, 2022 17:36
Show Gist options
  • Save JeffreyWay/6851dc65ec5ecfc1eba2213cee42ab70 to your computer and use it in GitHub Desktop.
Save JeffreyWay/6851dc65ec5ecfc1eba2213cee42ab70 to your computer and use it in GitHub Desktop.
PHP for Beginners, Episode 9 - Lambdas and Flexibility
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<?php
$books = [
[
'name' => 'Do Androids Dream of Electric Sheep',
'author' => 'Philip K. Dick',
'releaseYear' => 1968,
'purchaseUrl' => 'http://example.com'
],
[
'name' => 'Project Hail Mary',
'author' => 'Andy Weir',
'releaseYear' => 2021,
'purchaseUrl' => 'http://example.com'
],
[
'name' => 'The Martian',
'author' => 'Andy Weir',
'releaseYear' => 2011,
'purchaseUrl' => 'http://example.com'
],
];
$filteredBooks = array_filter($books, function ($book) {
return $book['releaseYear'] >= 1950 && $book['releaseYear'] <= 2020;
});
?>
<ul>
<?php foreach ($filteredBooks as $book) : ?>
<li>
<a href="<?= $book['purchaseUrl'] ?>">
<?= $book['name']; ?> (<?= $book['releaseYear'] ?>) - By <?= $book['author'] ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<?php
$books = [
[
'name' => 'Do Androids Dream of Electric Sheep',
'author' => 'Philip K. Dick',
'releaseYear' => 1968,
'purchaseUrl' => 'http://example.com'
],
[
'name' => 'Project Hail Mary',
'author' => 'Andy Weir',
'releaseYear' => 2021,
'purchaseUrl' => 'http://example.com'
],
[
'name' => 'The Martian',
'author' => 'Andy Weir',
'releaseYear' => 2011,
'purchaseUrl' => 'http://example.com'
],
];
$filteredBooks = array_filter($books, function ($book) {
return $book['author'] === 'Andy Weir';
});
?>
<ul>
<?php foreach ($filteredBooks as $book) : ?>
<li>
<a href="<?= $book['purchaseUrl'] ?>">
<?= $book['name']; ?> (<?= $book['releaseYear'] ?>) - By <?= $book['author'] ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>
@letmelivejba
Copy link

<title>Function & Filters</title> 'All the Light We Cannot See', 'published' => '2005', 'author' => 'Anthony Doerr', 'wiki' => 'https://en.wikipedia.org/wiki/All_the_Light_We_Cannot_See' ], [ 'name' => 'Wolf Totem', 'published' => '2004', 'author' => 'Jiang Rong', 'wiki' => 'https://en.wikipedia.org/wiki/Wolf_Totem' ], [ 'name' => 'The Fault in Our Stars', 'published' => '2012', 'author' => 'John Green', 'wiki' => 'https://en.wikipedia.org/wiki/The_Fault_in_Our_Stars' ], [ 'name' => 'Uncle Styopa', 'published' => '1936', 'author' => 'Sergel Stypa', 'wiki' => 'https://en.wikipedia.org/wiki/Uncle_Styopa' ], [ 'name' => 'Pride and Prejudice', 'published' => '1813', 'author' => 'Jane Austen', 'wiki' => 'https://en.wikipedia.org/wiki/Pride_and_Prejudice' ],
    ];

    function filter($datas, $fn) {
       $filteredData = [];

       foreach ($datas as $data) {
        if ($fn($data)) {
            $filteredData[] = $data;
        }
       }
     return $filteredData;
    };
     $filteredBooks = filter($books, function ($book){ 
        return $book['published'] >= 1930  && $book['published'] <= 2005;
     });
?>
<ul>
    <?php foreach ($filteredBooks as $book) : ?>
      
    <li>
            <a href="<?= $book['wiki']; ?>"> 
                 <?= $book['name']; ?> (<?= $book['published'] ?>) - By <?=  $book['author'] ?>
            </a>
    </li>
    <?php endforeach; ?>
</ul>

@AdolpheNkoranyiTresor
Copy link

AdolpheNkoranyiTresor commented Jun 6, 2023

List of books that were first published between the years 1950 and 2020:

<?PHP
       $allBooks = [
            [

            // In PHP, the correct syntax for array keys is the => character (equals sign followed by greater-than sign).

                'title' => 'Lion and the Mouse',
                'author' => 'Jerry Pinkney',
                'publishedYear' => 2009,
                'purchaseUrl' => 'https://en.wikipedia.org/wiki/The_Lion_%26_the_Mouse'
            ],
            [
                'title' => 'Are You My Mother?',
                'author' => 'P. D. Eastman',
                'publishedYear' => 1960,
                'purchaseUrl' => 'https://www.goodreads.com/book/show/197084.Are_You_My_Mother_'
            ],
            [
                'title' => 'Project Hail Mary',
                'author' => 'Andy Weir',
                'publishedYear' => 2021,
                'purchaseUrl' => 'https://www.amazon.com/Project-Hail-Mary-Andy-Weir/dp/0593135202'  
            ],
            [
                'title' => 'The Martian',
                'author' => 'Andy Weir',
                'publishedYear' => 2011,
                'purchaseUrl' => 'https://www.amazon.com/Martian-Andy-Weir/dp/0553418025'  
            ],
        ];


function filterBooks($items, $fn){
            $filteredItems = [];

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

            return $filteredItems;
        };

        $filteredBooks = filterBooks($allBooks, function ($book){
            return $book['publishedYear'] >= 1950 && $book['publishedYear'] <= 2020;
        });
    ?>

<ul>
    <?php foreach ($filteredBooks as $book) : ?>
        <li>
            <?= $book['title']; ?>
            <?= ' ' . 'was published in' . ' ' . $book['publishedYear'] . ' ' . 'and written by' . ' ' . $book['author'] . '.'; ?>
        </li>
    <?php endforeach; ?> 
</ul>  

image

@fppcnc
Copy link

fppcnc commented Aug 1, 2023

<h1>Recommended Books</h1>

<?php
$books = [
    [
        'name' => 'Book 1',
        'author' => 'Author 1',
        'purchaseUrl' => 'http://example1.com',
        'releaseDate' => 1998
    ],
    [
        'name' => 'Book 2',
        'author' => 'Author 2',
        'purchaseUrl' => 'http://example2.com',
        'releaseDate' => 1999
    ],
    [
        'name' => 'Book 3',
        'author' => 'Author 3',
        'purchaseUrl' => 'http://example3.com',
        'releaseDate' => 2015
    ],
    [
        'name' => 'Book 4',
        'author' => 'Author 1',
        'purchaseUrl' => 'http://example4.com',
        'releaseDate' => 2000
    ]
];


$filteredBooks = array_filter($books, function ($book) {
    return $book['releaseDate'] > 1950 && $book['releaseDate'] <= 2000 ;
});
?>
<ul>
    <?php foreach ($filteredBooks as $book) : ?>
        <li>
            <a href="<?= $book['purchaseUrl'] ?>">
                <?= $book['name'] ?> (<?= $book['releaseDate']; ?>) - By <?= $book['author'] ?>
            </a>
        </li>
    <?php endforeach; ?>
</ul>

@AdhiDevX369
Copy link

<body>
    <?php
    $books = [
        [
            'name' => 'Asahara',
            'author' => 'Blake Crouch',
            'urlToBuy' => 'www.buybooks.com/asahara',
            'releasedYear' => '2022'
        ],
        [
            'name' => 'Game Of thrones',
            'author' => 'George R. R. Martin',
            'urlToBuy' => 'www.buybooks.com/gameofthrones',
            'releasedYear' => '1996'
        ], [
            'name' => 'Forgot me or Not',
            'author' => 'Charitha Prawardhi Bandara, Chathuri Damayanthi',
            'urlToBuy' => 'www.buybooks.com/forgotmeornot',
            'releasedYear' => '2023'

        ], [
            'name' => 'Dark Matter',
            'author' => 'Blake Crouch',
            'urlToBuy' => 'www.buybooks.com/DarkMatter',
            'releasedYear' => '2016'

        ]
    ];

    /*! Define a Function 
        function $functionName(parameters ifyou need to add){
            Statement;
        }
    */
    //! Filter book By Author
    function filter($items, $fn)
    {
        $filteredItem = [];

        //*Function logic and statement
        foreach ($items as $item) {
            if ($fn($item)) {
                $filteredItem[] = $item;
            }
        }

        //*Return a value from function
        return $filteredItem;
    }

    $filteredBooks = filter($books, function ($book) {
        return $book['releasedYear'] >= 1950  && $book['releasedYear'] <=2020;
    });   

    //! Can Doit using Builtin Function
    $filtered = array_filter($books, function ($book) {
        return $book['releasedYear'] >= 1950  && $book['releasedYear'] <=2020;
    }); 
    ?>

    <h3 style="color: red;">Filter By Author</h3>
    <ul>
        <?php
        //* Called the function here
        foreach ($filtered as $book) : ?>
            <li>
                <a href="<?= $book['urlToBuy']; ?>">
                    <?= $book['name']; ?> (<?= $book['releasedYear']; ?>) By <?= $book['author']; ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>
</body>

@AdhiDevX369
Copy link

<body>
    <?php
    $books = [
        [
            'name' => 'Asahara',
            'author' => 'Blake Crouch',
            'urlToBuy' => 'www.buybooks.com/asahara',
            'releasedYear' => 2022
        ],
        [
            'name' => 'Game Of thrones',
            'author' => 'George R. R. Martin',
            'urlToBuy' => 'www.buybooks.com/gameofthrones',
            'releasedYear' => 1996
        ], [
            'name' => 'Forgot me or Not',
            'author' => 'Charitha Prawardhi Bandara, Chathuri Damayanthi',
            'urlToBuy' => 'www.buybooks.com/forgotmeornot',
            'releasedYear' => 2023

        ], [
            'name' => 'Dark Matter',
            'author' => 'Blake Crouch',
            'urlToBuy' => 'www.buybooks.com/DarkMatter',
            'releasedYear' => 2016

        ]
    ];

    /*! Define a Function 
        function $functionName(parameters ifyou need to add){
            Statement;
        }
    */
    //! Filter book By Author
    function filter($items, $key, $value)
    {
        $filteredItem = [];

        //*Function logic and statement
        foreach ($items as $item) {
            if ($item[$key] === $value) {
                $filteredItem[] = $item;
            }
        }

        //*Return a value from function
        return $filteredItem;
    }

    $filterByAuthor = filter($books, 'author', 'Blake Crouch');
    $filterByName  = filter($books, 'name', 'Asahara');
    $filterByYear = filter($books, 'releasedYear', 2023);
    ?>

    <h3 style="color: red;">Filter By Author</h3>
    <ul>
        <?php
        //* Called the function here
        foreach ($filterByAuthor as $book) : ?>
            <li>
                <a href="<?= $book['urlToBuy']; ?>">
                    <?= $book['name']; ?> (<?= $book['releasedYear']; ?>) By <?= $book['author']; ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>
    <h3 style="color: yellow;">Filter By Namer</h3>
        <ul>
            <?php
            //* Called the function here
            foreach ($filterByName as $book) : ?>
                <li>
                    <a href="<?= $book['urlToBuy']; ?>">
                        <?= $book['name']; ?> (<?= $book['releasedYear']; ?>) By <?= $book['author']; ?>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>

        <h3 style="color: green;">Filter By Year</h3>
        <ul>
            <?php
            //* Called the function here
            foreach ($filterByYear as $book) : ?>
                <li>
                    <a href="<?= $book['urlToBuy']; ?>">
                        <?= $book['name']; ?> (<?= $book['releasedYear']; ?>) By <?= $book['author']; ?>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
</body>

@juanmarcoso
Copy link

<h1>
    Libros recomendados
</h1>    
<?php 
    $books = [
        [
            'name' => 'Do Androids Dream of Electric Sheep',
            'author' => 'Philip K. Dick',
            'releaseYear' => 1968,
            'purchaseUrl' => 'http://example.com'
        ],
        [
            'name' => 'Project Hail Mary',
            'author' => 'Andy Weir',
            'releaseYear' => 2021,
            'purchaseUrl' => 'http://example2.com'
        ],
        [
            'name' => 'The Martians',
            'author' => 'Andy Weir',
            'releaseYear' => 2011,
            'purchaseUrl' => 'http://example3.com'
        ],
    ];
    $filteredBooks = array_filter ($books, function($book) {
        return $book['releaseYear']; if ($book['releaseYear'] === (1950 && 2020));

    });
?>
<ul>
    <?php foreach ($filteredBooks as $book) : ?>
        
            <li>
                <a href="<?= $book['purchaseUrl'] ?>">
                    <?= $book['name']; ?> (<?= $book['releaseYear'] ?>) - By <?= $book['author'] ?>
                </a>
            </li>
        
    <?php endforeach ; ?>
</ul>

@codelyftlab
Copy link

<?php
$books = [
    [
        'title' => 'Hail Mary',
        'author' => 'Drew',
        'purchaseUrl' => 'https://example.com',
        'releaseYear' => 2001
    ],
    [
        'title' => 'Project Hail Mary',
        'author' => 'Wer',
        'purchaseUrl' => 'https://example.com',
        'releaseYear' => 1990
    ],
    [
        'title' => 'Projects Hail Mary',
        'author' => 'Wer',
        'purchaseUrl' => 'https://example.com',
        'releaseYear' => 2020
    ],
];

$filterBooks = array_filter($books, function ($book) {
    return $book['releaseYear'] >= 1950 && $book['releaseYear'] <= 2020;
});
?>

<?php foreach ($filterBooks as $book) : ?>
    <li>
        <?= $book['title'] ?>
    </li>
<?php endforeach; ?>

@bollie-dev
Copy link

"The dragon fly", "release_year" => 1978, "author" => "James Dio", "purchase_url" => "http://example.com"], ["book_title" => "The serial killer", "release_year" => 1958, "author" => "Jackon Duo", "purchase_url" => "http://example.com"], ["book_title" => "Politics", "release_year" => 1988, "author" => "Ellen Marshall", "purchase_url" => "http://example.com"], ["book_title" => "Sweet heart", "release_year" => 2022, "author" => "James Dio", "purchase_url" => "http://example.com"] ]; function filter($items, $fn) { $filteredItems = []; foreach ($items as $item) { if ($fn($item)) { $filteredItems[] = $item; } } return $filteredItems; }; $filteredBooks = array_filter($books, function ($book) { return $book["author"] === "Ellen Marshall"; }); ?> <title>Library Books</title>
<ul>
    <h2>Selected titles</h2>
    <?php foreach ($filteredBooks as $item) :  ?>
        <li>Click book link to purchase:
            <a href="<?= $item["purchase_url"] ?>">
                <?= $item["author"] ?> >>
                <?= $item["book_title"] ?>
                (<?= $item["release_year"] ?>)

            </a>
        </li>
    <?php endforeach; ?>
</ul>

@spacemark3
Copy link

$filteredBooks = array_filter($books, function ($book) { return $book['year'] >= 1950 && $book['year']<= 2020; });

@dillony04
Copy link

dillony04 commented Feb 20, 2024

    <?php
        $movies = [
                [
                        'name' => 'Fast n Furious',
                        'releaseDate' => 2002
                ],
                [
                        'name' => 'Terminator 2',
                        'releaseDate' => 1998
                ],
                [
                        'name' => 'Power Book II',
                        'releaseDate' => 2020
                ],
        ];

       /*function filterByDate($movies, $releaseDate) {

            $filterMovies = [];

           foreach ($movies as $movie) {
            if ($movie['releaseDate'] >= $releaseDate) {
                $filterMovies[] = $movie;
            }
        }
    return $filterMovies;
    }*/

    $filterByDate = array_filter($movies, function($movie){
        return $movie['releaseDate'] >= 1950 && $movie['releaseDate'] <= 2020;
    });

    ?>

    <ul>
        <?php foreach ($filterByDate as $movie): ?>
            <li>
              <?= $movie['name'] ?>
            </li>
        <?php endforeach; ?>
    </ul>

</body>

@K1LLERB0T
Copy link

$filteredBooks = array_filter($books, function ($book) { return $book['releaseYear'] >= 1950 && $book['releaseYear'] <= 2020; });

@binsarkiel
Copy link


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
</head>

<body>
<?php
$books = [
    [
        'name' => 'Do Androids Dream of Electric Sheep',
        'author' => 'Philip K. Dick',
        'releaseYear' => 1968,
        'purchaseUrl' => 'http://example.com'
    ],
    [
        'name' => 'Project Hail Mary',
        'author' => 'Andy Weir',
        'releaseYear' => 2021,
        'purchaseUrl' => 'http://example.com'
    ],
    [
        'name' => 'The Martian',
        'author' => 'Andy Weir',
        'releaseYear' => 2011,
        'purchaseUrl' => 'http://example.com'
    ],
];



$filteredBooks = array_filter($books, function ($book) {
    return $book['releaseYear'] >= 1950 && $book['releaseYear'] <= 2020;
});

?>

<h1>Recommended Books</h1>

<ul>
    <?php foreach ($filteredBooks as $book) : ?>
        <li>
            <a href="<?= $book['purchaseUrl'] ?>">
                <?= $book['name']; ?> (<?= $book['releaseYear'] ?>) - By <?= $book['author'] ?>
            </a>
        </li>
    <?php endforeach; ?>
</ul>
</body>
</html>

@SIFAT-AOC
Copy link

  

<?php 
$cars = [
  ['name' => "Supra",
  'date' => 1990],
  [
    'name' => 'Marcedes Benz',
    'date' => 1901
  ],
  [
    'name' => 'Ferrari',
    'date' => 1927
  ]
];
function filter($items , $fn){
    $filterItems= [];
    foreach($items as $item){
      if($fn($item)){
        $filterItems[] = $item;
      }
    }
return $filterItems;
};
$findbyDate = array_filter($cars, function ($car){
 return $car['date'] > 1910 && $car['date'] <= 1990;
});

?>

<ul>
  <?php foreach($findbyDate as $car): ?>
    <li>
      <?= $car['name'] ?>
    </li>
    <?php endforeach; ?>
</ul>
</body>

@Rofiaziztr
Copy link

<!doctype html>

<title>Demo</title>
<h1>A list of Movies:</h1>
<?php
    $books = [
        [
            'name' => 'Inception: The Shooting Script',
            'author' => 'Christopher Nolan & Jonathan Nolan',
            'releaseYear' => 2010,
            'purchaseUrl' => 'http://example.com'
        ],
        [
            'name' => 'The Nightingale',
            'author' => 'Kristin Hannah',
            'releaseYear' => 2021,
            'purchaseUrl' => 'http://example.com'
        ],
        [
            'name' => '1000 Years of Joys and Sorrows',
            'author' => 'Xiaolu Guo',
            'releaseYear' => 2021,
            'purchaseUrl' => 'http://example.com'
        ],
        [
            'name' => 'Rita Hayworth and Shawshank Redemption',
            'author' => 'Stephen King',
            'releaseYear' => 1982,
            'purchaseUrl' => 'http://example.com'
        ],
        [
            'name' => 'Batman: The Dark Knight Returns',
            'author' => 'Frank Miller',
            'releaseYear' => 1986,
            'purchaseUrl' => 'http://example.com'
        ],
        [
            'name' => 'Pulp Fiction: A Quentin Tarantino Screenplay',
            'author' => 'Quentin Tarantino',
            'releaseYear' => 1994,
            'purchaseUrl' => 'http://example.com'
        ],
        [
            'name' => 'Forrest Gump',
            'author' => 'Winston Groom',
            'releaseYear' => 1986,
            'purchaseUrl' => 'http://example.com'
        ]
    ];
    

    function filter($items, $fn) 
    {
        $filteredItems = [];

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

        return $filteredItems;
    }

    $filteredBooks = filter($books, function ($book) {
        return $book['releaseYear'] >= 1950 && $book['releaseYear'] <= 2020;
    });
?>

<?php foreach ($filteredBooks as $book) : ?>
    <ul>
        <li>
            <a href="<?= $book['purchaseUrl'] ?>">
                <?= $book['name']; ?> (<?= $book['releaseYear'] ?>) - By <?= $book['author'] ?>
                </a>
            </li>
    </ul>
<?php endforeach; ?>

@saifull03
Copy link

<title>Document</title> 'Forrest Gump', 'director' => 'Gus Van Sant', 'released' => '1930'
    ],

    [
        'name' => 'Shawshank Redemption',
        'director' => 'Frank Darabont',
        'released' => '1950'
    ],
    [
        'name' => 'Good Will Hunting',
        'director' => 'Gus Van Sant',
        'released' => '2000'
    ],
    [
        'name' => 'Fight Club',
        'director' => 'Gus Van Sant',
        'released' => '2030'
    ],
    [
        'name' => 'American Phycho',
        'director' => 'Gus Van Sant',
        'released' => '2015'
    ],

];

function filter($items, $fn)
{
    $filteredItems = [];

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

//we can handle the comparison by ourselves


$filteredMovie = filter($movies,  function ($movie) {
    return $movie['released'] >= 1950 && $movie['released'] <= 2020;
});
?>



<ul>
    <?php
    foreach ($filteredMovie as $movie) : ?>
        <li>

            <?= $movie['name']  ?> (<?= $movie['released'] ?>)
        </li>

    <?php endforeach; ?>

</ul>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment