w3resource
php Programming Exercies

PHP Challenges: Find the length of the last word in a string

PHP Challenges - 1: Exercise-24 with Solution

Input : PHP Exercises

Write a PHP program to find the length of the last word in a string.

Explanation :

PHP: Find the length of the last word in a string

Sample Solution :

PHP Code :

<?php
function length_of_last_word($s)
{
      
        if (strlen(trim($s)) == 0)
        {
            return "Blank String";
        }
        
        $words = explode(' ', $s);
        
        if (sizeof($words) >1)
        return strlen(substr($s, strrpos($s, ' ') + 1));
        else
        return "Single word";
        
        
}
print_r(length_of_last_word("PHP Exercises")."\n");
print_r(length_of_last_word("PHP")."\n");
print_r(length_of_last_word("")."\n");
print_r(length_of_last_word("  ")."\n");
?>

Sample Output:

9                                                           
Single word                                                 
Blank String                                                
Blank String   

Flowchart:

PHP Flowchart: Find the length of the last word in a string

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to find majority element in an array.
Next: Write a PHP program to find the single number which occurs odd number of times and other numbers occur even number of times.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming