Menu
Coddy logo textTech

Filtering with 'array_filter'

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

The array_filter() function is designed to create a new array containing only the elements that meet specific criteria. Unlike array_map() which transforms every element, array_filter() selectively keeps elements based on whether they pass a test.

When used without a callback function, array_filter() automatically removes all "empty" values from an array. PHP considers several values as empty: false, null, 0, empty strings "", and empty arrays.

<?php
$mixedData = ["hello", 0, "world", false, null, "PHP", ""];
$cleanedData = array_filter($mixedData);
// Result: ["hello", "world", "PHP"]
?>

This behavior makes array_filter() extremely useful for cleaning up data arrays. The original array remains unchanged, and you get a new array with only the meaningful values. This is particularly helpful when processing user input or working with data that might contain unwanted empty values.

challenge icon

Challenge

Easy

You will receive one input: a comma-separated list of survey responses containing various data types including numbers, empty strings, zeros, and text responses. The input will be in the format yes,0,,no,5,,true,false,answer.

Read the input, convert the comma-separated values into an array, use array_filter() without a callback function to remove all empty values, and print each remaining value on a separate line in the order they appear.

Remember that array_filter() without a callback automatically removes values that PHP considers empty: false, null, 0, empty strings "", and empty arrays.

Input format: One line containing comma-separated values (example: yes,0,,no,5,,true,false,answer)

Expected output: Each non-empty value printed on a separate line in the order they appear in the filtered array

Try it yourself

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

// Convert comma-separated values into an array
$responses = explode(',', $input);

// TODO: Write your code below
// Use array_filter() to remove empty values and print each remaining value


?>
quiz iconTest yourself

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

All lessons in Logic & Flow