PHP Function array_reduce

PHP array_reduce() function is used to reduce an array to a single value using a callback function. The callback function takes two arguments: the accumulator and the current value of the array. The accumulator is the result of the previous iteration, or the initial value if it’s the first iteration.

To find the number of unique books in an array of books, we can use array_reduce() along with an array to keep track of the unique books we’ve encountered so far.

Example 1 (Unique books count):

$books = [
[‘title’ => ‘Book 1’, ‘author’ => ‘Author 1’],
[‘title’ => ‘Book 2’, ‘author’ => ‘Author 2’],
[‘title’ => ‘Book 1’, ‘author’ => ‘Author 3’],
[‘title’ => ‘Book 3’, ‘author’ => ‘Author 1’],
[‘title’ => ‘Book 2’, ‘author’ => ‘Author 3’]
];

$uniqueBooks = array_reduce($books, function($carry, $book) {
// Check if the title of the book has already been encountered
if (!in_array($book[‘title’], $carry)) {
// Add the title of the book to the array of encountered titles
$carry[] = $book[‘title’];
}
return $carry;
}, []);

$numUniqueBooks = count($uniqueBooks);
echo “There are $numUniqueBooks unique books in the array.”;

Output: There are 3 unique books in the array.

In the above example, we initialize the accumulator as an empty array ([]) and check if the title of each article has already been encountered using in_array(). If the title hasn’t been encountered, we add it to the array of encountered titles. The final result is the array of unique book titles, which we can count using count() to get the total number of unique books.

 

Example 2 (Search book in the nested array by id):

$books = array(
array(“id” => 1,”name” => “Tally”),
array(“id” => 2,”name” => “Basic”),
array(“id” => 3,”name” => “Java”),
);
$bid = 2;
$result = array_reduce($books, function ($carry, $item) use ($bid) {
return $item[“id”] == $bid ? $item[“name”] : $carry;
});
echo “For book id “.$bid.” Book name is “.$result;

Output: For book id 2 Book name is Basic

In the above example, we are searching for the book name in the nested array by book id i.e. $bid.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.