Important, must read
I hope that you have setup your vs code application on your system.
If you don't have then followed this link https://code.visualstudio.com/download to download vs code for practice to learn PHP.
Diving in code 🐬
In a fresh vs code project (version 1.90 at the time of creation), we need following dependencies:
- HTML
- CSS
- PHP
- Function and filter
- Lamda function
On VS Code Side 😎
- Document Type
<!DOCTYPE html>
It tells that document is in HTML type 5.
HTML5 Structure
Basic structure to write a document in HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>You have read in dark mode </h1>
</body>
</html>
CSS on body tag
<style>
body {
display: grid;
place-items: center;
font-family: sans-serif;
height: 100px;
margin: 20px;
}
</style>
Function to filter books by author
Functions are initialised once in code and then these are used in their scope by calling them with name that is given at declaration time. Let sum is a function and it's function call is as sum();
<?php
function filterBooksByAuthor($books, $author) {
$filteredBooks = array_filter($books, function($book) use ($author) {
return $book['author'] == $author;
});
return $filteredBooks;
}
Array of books
$books = [
['name' => 'Web', 'author' => 'Philip K. Dick', 'purchaseUrl' => 'http://example.com'],
['name' => 'OOP', 'author' => 'Andy Weir', 'purchaseUrl' => 'http://example.com'],
['name' => 'Database', 'author' => 'Jeffery', 'purchaseUrl' => 'http://example.com']
];
Filter books by author using the function
$filteredBooks = filterBooksByAuthor($books, 'Andy Weir');
List of filtered books
When this code execution is completed, it shows a list of filtered books as a output.
<ul>
<?php foreach ($filteredBooks as $book) : ?>
<li><?= $book['name']; ?> - by <?= $book['author'] ?></li>
<?php endforeach; ?>
</ul>
Lamda function in PHP
Lamda/Anonymous functions have no name at the time of declaration. These can be used with variables.
<?php
$sum = function($a, $b) {
return $a + $b;
};
echo "Result of lambda function: " . $sum(3, 4);
?>
I hope that you have understand everything clearly.
Thanks for reading 😘🤗
Top comments (0)