Monday, October 6, 2025
HomeLanguagesHow to find number of characters in a string in PHP ?

How to find number of characters in a string in PHP ?

We have given a string and the task is to count number of characters in a string str in PHP. In order to do this task, we have the following methods in PHP:

Method 1: Using strlen() Method: The strlen() method is used to get the length of a given string str. Length of the string including all the white spaces and special characters in this method.

Syntax:

strlen( $string )

Example :

PHP




<?php
// PHP program to count all
// characters in a string 
    
$str = "  Geeks for Geeks  "; 
    
// Using strlen() function to
// get the length of string
$len = strlen($str);
  
// Printing the result
echo $len; 
?>


Output

19

Method 2: Using mb_strlen() Method: The mb_strlen() method is used to return the number of characters in a string having character encoding. A multi-byte character is counted as 1.

Syntax:

mb_strlen($str, $encoding);

Note: Before using this function, install the php7.0-mbstring package using the following command:

sudo apt install php7.0-mbstring

Example :

PHP




<?php
// PHP program to count all
// characters in a string 
    
$str = "  Geeks for Geeks  "; 
    
// Using mb_strlen() function 
// to get the length of string
$len = mb_strlen($str);
  
// Printing the result
echo $len; 
?>


Output

19

Method 3: Using iconv_strlen() Method: The iconv_strlen() method is used to get the character count of a string, as an integer.

Syntax:

int iconv_strlen( string $str, 
    string $charset = ini_get("iconv.internal_encoding"))

Example :

PHP




<?php
// PHP program to count number
// of characters in a string 
    
$str = "  Geeks for Geeks  "; 
    
// Using iconv_strlen() function 
// to get the length of string
$len = iconv_strlen($str);
  
// Printing the result
echo $len; 
?>


Output

19

Method 4: Using grapheme_strlen() Method: The grapheme_strlen() method is used to get the string length in grapheme units (not bytes or characters).

Syntax:

int grapheme_strlen(string $input)

Example :

PHP




<?php
// PHP program to count number
// of characters in a string 
    
$str = "  Geeks for Geeks  "; 
    
// Using grapheme_strlen() function 
// to get the length of string
$len = grapheme_strlen($str);
  
// printing the result
echo $len; 
?>


Output

19
RELATED ARTICLES

Most Popular

Dominic
32338 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6825 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6780 POSTS0 COMMENTS