DEV Community

ebube samuel nworie
ebube samuel nworie

Posted on

Understand how to filter an array of items using php -part1

This is the first part of a four-part series on filtering an array of items using the PHP programming language.

Introduction

Array filtering is a common algorithm used by software developers to create filter options in software applications. These filters enable businesses using the software application to organize and display specific sets of items, such as books, music, or ordered items. In this series, I'll guide you through a step-by-step approach to filtering items using PHP programming language. While the logic remains consistent across programming languages, the syntax may vary.

Prerequisites:

This article is designed for beginners, although a basic understanding of programming would be beneficial.
Using an Integrated Development Environment (IDE) like Visual Studio Code or PHPStorm is recommended.

Table of Contents:

Introduction
Prerequisites
Body
Conclusion

Body:

In this series, we'll work with a list of books containing book titles and author names, and we’ll be filtering the books by their authors.

Start by creating an array named $bookItems in PHP. Variables in PHP are declared using the $ sign.

<?php 
$bookItems = [
    [
        'author' => 'Debra Fine',
        'book' => 'The Fine Art of Small Talk'
    ],
    [
        'author' => 'David Goggins',
        'book' => 'Can\'t Hurt Me’    ],
],
[
‘author’=> ’David Goggins’
 'book' => 'Built not born’    
],
    [
        'author' => 'Debra Fine',
        'book' => 'The big talk’
    ],


]
?>

Enter fullscreen mode Exit fullscreen mode

Next, create a function named filterByAuthor that accepts two parameters: the $bookItems array and the value to filter by, in this case, $author.

<?php
function filterByAuthor($bookItems, $author) {
    $filteredBooks = [];
    foreach ($bookItems as $bookItem) {
        if ($bookItem['author'] === $author) {
            $filteredBooks[] = $bookItem;
        }
    }
    return $filteredBooks;
}
?>

Enter fullscreen mode Exit fullscreen mode

To display the filtered books, use a loop over the result returned by the filterByAuthor function, in this case we use the foreach loop :

<?php foreach (filterByAuthor($bookItems, 'David Goggins') as $book): ?>
    <h1><?php echo $book['book']; ?> by <?php echo $book['author']; ?></h1>
<?php endforeach; ?>

Enter fullscreen mode Exit fullscreen mode

Conclusion:

This article shows how to filter an array of book items by their author using PHP. In the next article of this series, we'll focus on refactoring this code for better efficiency.

Feel free to ask any questions in the comment section below.

Top comments (0)