PHP: Length of each word

Apply a function to every item of a list with array_map.

What to build

A program that prints the length of every word.

Requirements

  • Read one line of words separated by single spaces.
  • Print the length of each word, separated by spaces, then Total: T with the sum of the lengths.

Input

One line of words.

Output

Two lines.

Constraints

1 to 50 words, each with 1 to 20 letters.

Example

Input:

the quick brown fox

Output:

3 5 5 3
Total: 16

Why it works

array_map applies strlen to every word, and array_sum adds the lengths.

Examples

Example 1 · Input
the quick brown fox
Expected output
3 5 5 3
Total: 16
Example 2 · Input
a
Expected output
1
Total: 1

Hints

Hint 1

explode(" ", $line) splits the line into words.

Hint 2

array_map('strlen', $words) gives the lengths.

Solution

Show one correct solution (try it yourself first)
<?php
$words = explode(" ", trim(fgets(STDIN)));
$lengths = array_map('strlen', $words);
echo implode(" ", $lengths), "\n";
echo "Total: ", array_sum($lengths), "\n";

▶ Open this solution in the compiler

Lesson: String and array functions →