Menu
Coddy logo textTech

'array_filter' with Custom Fun

Part of the Logic & Flow section of Coddy's PHP journey — lesson 42 of 68.

While array_filter() without a callback removes empty values, its true power emerges when you provide a custom callback function. This allows you to define exactly which elements should be kept based on your specific criteria.

To use a custom function with array_filter(), pass your function name as the second parameter. Your callback function should accept one parameter (the current array element) and return true to keep the element or false to exclude it.

<?php
function isEven($number) {
    return $number % 2 === 0;
}

$numbers = [1, 2, 3, 4, 5, 6, 7, 8];
$evenNumbers = array_filter($numbers, "isEven");
// Result: [2, 4, 6, 8]
?>

In this example, the isEven function tests each number using the modulo operator. Only numbers that return true (even numbers) are included in the filtered result. This approach gives you complete control over the filtering logic, making array_filter() incredibly versatile for data processing tasks.

challenge icon

Challenge

Easy

You will receive two inputs: a comma-separated list of product prices and a minimum price threshold. The first input contains prices as a string in the format 15.99,45.00,8.50,120.00,22.75, and the second input is the minimum price threshold as a number (example: 20).

Read both inputs, convert the comma-separated prices into an array of numbers, create a custom callback function that checks if a price is greater than or equal to the threshold, use array_filter() with your custom function to keep only prices that meet the threshold, and print each filtered price on a separate line in the order they appear.

Your custom callback function should accept one parameter (the price) and return true if the price is greater than or equal to the threshold, or false otherwise.

Input format:

  • First line: Comma-separated product prices (example: 15.99,45.00,8.50,120.00,22.75)
  • Second line: Minimum price threshold as a number (example: 20)

Expected output: Each price that meets or exceeds the threshold printed on a separate line, maintaining the original order

Try it yourself

<?php
// Read input
$prices_input = trim(fgets(STDIN));
$threshold = floatval(fgets(STDIN));

// Convert comma-separated prices to array
$prices = array_map('floatval', explode(',', $prices_input));

// TODO: Write your code below
// Create a custom callback function that checks if a price >= threshold
// Use array_filter() with your custom function
// Print each filtered price on a separate line

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow