Open In App

How to Find the Length of a String in PHP?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The length of a string is the number of characters it contains. In PHP, determining the length of a string is a common task and can be achieved using various approaches.

Using strlen() function:

PHP strlen() calculates the length of a string in bytes.

$string = "geeksforgeeks";
$length = strlen($string);
echo "Length using strlen(): $length";

Utilizing mb_strlen() function

PHP mb_strlen() accurately counts the number of characters in a string, particularly useful for multibyte encodings like UTF-8.

$string = "geeksforgeeks";
$length = mb_strlen($string, 'UTF-8');
echo "Length using mb_strlen(): $length";

Using a loop

This method iterates through each character in the string and counts them.

$string = "geeksforgeeks";
$length = 0;
for ($i = 0; isset($string[$i]); $i++) {
$length++;
}
echo "Length using loop: $length";

Using str_word_count( )

Although designed to count words, str_word_count() can indirectly determine string length by providing the number of words.

$string = "geeksforgeeks";
$wordCount = str_word_count($string);
echo "Word count using str_word_count(): $wordCount";


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads