Challenge - Longest Word
Part of the Fundamentals section of Coddy's PHP journey — lesson 70 of 71.
Challenge
EasyRead one line of input:
- A sentence containing multiple words separated by spaces (e.g.,
The quick brown fox)
Create a function called findLongestWord that accepts one parameter:
$sentenceasstring
The function should have a return type declaration of string and find the longest word in the sentence.
Call the function with the input value and print the returned result.
Note: If multiple words have the same longest length, return the first one encountered.
For example:
"The quick brown fox" → "quick" (6 characters)
"I love programming" → "programming" (11 characters)To solve this, you'll need to break the sentence into individual words. PHP's explode() function is perfect for this—it splits a string into an array based on a delimiter:
<?php
$words = explode(" ", "hello world");
// $words is now ["hello", "world"]
?>Try it yourself
<?php
// Read input
$sentence = trim(fgets(STDIN));
// TODO: Create the findLongestWord function below
// - Accept $sentence as a string parameter
// - Add return type declaration of string
// - Use explode() to split the sentence into words
// - Loop through the array to find the longest word using strlen()
// - Return the longest word (first one if there's a tie)
// Call the function and print the result
echo findLongestWord($sentence);
?>All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators