Challenge: Unique Item Filter
Part of the Logic & Flow section of Coddy's PHP journey — lesson 68 of 68.
Challenge
EasyYou 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
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise7Working with Dates and Times
The 'date()' FunctionUnix Timestamps with 'time()'Intro to the DateTime ObjectFormatting DateTime ObjectsModifying DateTime ObjectsRecap: Date Calculations10Final Challenges
Challenge: Palindrome CheckerChallenge: Character FrequencyChallenge: Shopping Cart TotalChallenge: Unique Item Filter2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting