Home

>

Prompts Database

>

Programming
Custom Filter Function Development in [Language] for [Data Structure]
avatar
Buffy Summers
Share
Leave a comment
616 days ago

Prompt type:

Write code

Category:

Programming, Coding

Media type:

Use with AI:

ChatGPT from OpenAI
View Full Output

Example output

Here's the PHP function based on these inputs:

<?php function filterProductsByCondition($productsArray, $categoryToFilter, $minPrice) { $filteredProducts = array_filter($productsArray, function($product) use ($categoryToFilter, $minPrice) { return $product['category'] === $categoryToFilter && $product['price'] > $minPrice; }); return $filteredProducts; } // Example usage: $products = [ ['id' => 1, 'name' => 'Laptop', 'price' => 800, 'category' => 'Electronics'], ['id' => 2, 'name' => 'Headphones', 'price' => 60, 'category' => 'Electronics'], ['id' => 3, 'name' => 'T-shirt', 'price' => 25, 'category' => 'Clothing'], ['id' => 4, 'name' => 'Smartphone', 'price' => 120, 'category' => 'Electronics'], ]; $categoryToFilter = 'Electronics'; $minPrice = 50; $filteredProducts = filterProductsByCondition($products, $categoryToFilter, $minPrice); print_r($filteredProducts); ?>

In this function:

  • $productsArray is the array of products.
  • $categoryToFilter is the category we want to filter by (in this case, "Electronics").
  • $minPrice is the minimum price threshold for filtering products.
  • The function uses array_filter to iterate through the products and apply the filtering condition based on category and price.
  • It returns an array containing only the products that meet the filtering condition.

When you run this code with the example data provided, it will output the filtered array containing only the electronics products with a price higher than $50.

Description or instructions

This prompt is about developing a function in a specific programming language to filter a given data structure based on a specified condition. It includes defining input variables, specifying the condition for filtering, and describing the expected output.

Prompt

Write a [language] function to filter [data structure] based on [condition] with the following inputs: [input variables] and expected output: [output description].