Menu
Coddy logo textTech

Challenge - Longest Word

Part of the Fundamentals section of Coddy's PHP journey — lesson 70 of 71.

challenge icon

Challenge

Easy

Read 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:

  • $sentence as string

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