Challenge: Character Frequency
Part of the Logic & Flow section of Coddy's PHP journey — lesson 66 of 68.
Challenge
EasyYou will receive a single input: a string of text.
The input will be a string in this format: hello world
Read the input string. Count the frequency of each character in the string (case-insensitive), excluding spaces. Store the character frequencies in an associative array where the keys are the characters and the values are their counts.
Sort the associative array by key in ascending alphabetical order using ksort().
Print each character and its frequency in the following format:
[character]: [count]
Print each character-frequency pair on a separate line, in alphabetical order.
Input format:
- A single line containing a string of text (example:
hello world)
Expected output: Each character and its frequency printed on a separate line in the format: [character]: [count], sorted alphabetically by character
Try it yourself
<?php
// Read input
$text = trim(fgets(STDIN));
// TODO: Write your code below
// 1. Convert the string to lowercase
// 2. Count character frequencies (excluding spaces)
// 3. Sort the array by key using ksort()
// 4. Print each character and its frequency
?>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