w3resource logo


php exercises

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

PHP Challenges - 1: Exercise-24 with Solution

Input : PHP Exercises
Output : 9

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");
?>

Output :

9                                                           
Single word                                                 
Blank String                                                
Blank String   

Flowchart:

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

PHP Code Editor:

<?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");
?>

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number