Menu
Coddy logo textTech

Challenge: Unique Item Filter

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

challenge icon

Challenge

Easy

You will receive a single input: a comma-separated string of items that may contain duplicates.

The input will be a string in this format: apple,banana,apple,orange,banana,grape,apple

Read the input string and split it into an array of items. Use array_filter() with a custom callback function to remove duplicate items, keeping only the first occurrence of each unique item.

To accomplish this, create a callback function that tracks which items have already been seen. The callback should return true for items encountered for the first time and false for duplicates. You can use a variable outside the callback and capture it by reference with use (&$seen) so updates persist across the calls array_filter makes to the callback.

After filtering, print each unique item on a separate line in the order they first appeared in the original input.

Input format:

  • A single line containing comma-separated items (example: apple,banana,apple,orange)

Expected output: Each unique item printed on a separate line, in the order of their first appearance in the input

Try it yourself

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

// Split the input into an array
$items = explode(',', $input);

// TODO: Write your code below
// Use array_filter() with a custom callback function to remove duplicates


// Output each unique item on a separate line

?>

All lessons in Logic & Flow