How to calculate the length of a string in PHP
There are two ways to calculate the length of a string in PHP, which are as follows:
The strlen function
We can use the strlen function to calculate the length of a string measured in bytes. The strlen function accepts a string argument and returns an integer. It has been available since PHP version 4.
The strlen function is used when:
- The string only contains single-byte characters.
- We want to know the storage size of the string.
Code example
<?php$myString = 'Hello world';echo strlen($myString);
Code explanation
- Line 3: We set the
$myStringvariable to the valueHello world. - Line 5: We use the
strlenfunction to calculate the length of the string, and we print the result using theechocommand.
The mb_strlen function
The mb_strlen function is part of the mbstring PHP extension. It returns the length of a string in multi-byte characters. The mb_strlen function accepts a string argument and returns an integer.
The mb_strlen function accepts a second optional argument describing the character encoding type, e.g., UTF-8. If the encoding is not provided, the internal encoding for the mbstring extension is used.
The mb_strlen function has been available since PHP version 4.06. We need to install the mbstring extension in order to use it.
The mb_strlen function is used when the string may contain multi-byte characters, and we want to know the number of characters in the string.
Code example
<?php$myString = '€10.00';echo mb_strlen($myString, 'UTF-8');
Code explanation
- Line 3: We set the value of the
$myStringvariable to€10.00, where the symbol€is a multi-byte character. - Line 5: We use the
mb_strlenfunction to calculate the length of the$myStringvariable. We print the result using theechocommand.
Free Resources