Searching Products by Price and Availability in PHP

By Shahnail Khan Last updated : April 11, 2024

In this example, we will learn how to search products by price and availability using PHP array and array methods.

Searching Products by Price and Availability

To search products by price and availability, you need to write a custom callback function that should contain the logical operation to return the products based on the given price and availability and then use the array_filter() method to get the filtered products.

PHP Program for Searching Products by Price and Availability

The following PHP source code has the product data and returns the filtered products based on the given price and availability.

<?php
// let's consider an array representing products
$products = [
    ["name" => "Laptop", "price" => 1200, "available" => true],
    ["name" => "Smartphone", "price" => 500, "available" => false],
    ["name" => "Headphones", "price" => 80, "available" => true],
    ["name" => "Earbuds", "price" => 99, "available" => true],
    // ... more products
];

// Custom callback function for filtering
function filterProducts($product)
{
    return $product["available"] && $product["price"] < 100;
}

// Filtering the array
$filteredProducts = array_filter($products, "filterProducts");

// Displaying the results
print_r($filteredProducts);

?>

Output

The output of the above program is:

Array
(
    [2] => Array
        (
            [name] => Headphones
            [price] => 80
            [available] => 1
        )

    [3] => Array
        (
            [name] => Earbuds
            [price] => 99
            [available] => 1
        )

)

Explanation

  • The filterProducts function defines the conditions for filtering products.
  • The array_filter() is used to apply this function to each product in the array, retaining only those that meet the criteria.
  • In this case, it will output available products with a price under $100.

To understand the above example, you should have the knowledge of the following PHP Topics:

More PHP Array Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.