
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP program to find the length of the last word in the string
To find the length of the last word in the string, the PHP code is as follows −
Example
<?php function last_word_len($my_string){ $position = strrpos($my_string, ' '); if(!$position){ $position = 0; } else { $position = $position + 1; } $last_word = substr($my_string,$position); return strlen($last_word); } print_r("The length of the last word is "); print_r(last_word_len('Hey')."
"); print_r("The length of the last word is "); print_r(last_word_len('this is a sample')."
"); ?>
Output
The length of the last word is 3 The length of the last word is 6
A PHP function named ‘last_word_len’ is defined, that takes a string as the parameter −
function last_word_len($my_string) { // }
The first occurrence of the space inside another string is found by using the ‘strrpos’ function. If that position is present, it is assigned to 0. Otherwise, it is incremented by 1 −
$position = strrpos($my_string, ' '); if(!$position){ $position = 0; } else{ $position = $position + 1; }
The substring of the string, based on the position is found, and the length of this string is found and returned as output. Outside this function, the function is called by passing the parameter, for two different samples and the output is printed on the screen.
- Related Articles
- Python - Find the length of the last word in a string
- PHP program to find the first word of a sentence
- Length of Last Word in C++
- Function to find the length of the second smallest word in a string in JavaScript
- PHP program to find the number of characters in the string
- Finding the length of second last word in a sentence in JavaScript
- C# program to find the index of a word in a string
- C++ Program to Find the Length of a String
- C program to find the length of a string?
- Golang Program to find the length of a string
- Find the first maximum length even word from a string in C++
- Program to find length of longest diminishing word chain in Python?
- Find First and Last Word of a File Containing String in Java
- MySQL query to split the string “Learn With Ease” and return the last word?
- Python Program to return the Length of the Longest Word from the List of Words

Advertisements