How to find the length of a string in PHP - strlen, mb_strlen
Last updated: Aug 29, 2022
Colleagues hello to all.
In today's article, we'll talk about how to find out the length of a string in PHP.
Whenever we work with string variables or with other objects in php that are related to a string, then we very often need to find out the length of this very string in order to further it back. The task seems very simple, but there is one very important nuance, this is encoding. Functions in PHP that calculate the size of a string can show different values, and the length values will depend on what encoding you use on your site.
PHP has several built-in functions that determine the size of a string, and we'll look at them today.
The first function we'll look at is called strlen. The strlen function works very simply, it takes only one single and required parameter, which is a string, and returns the length of the string.
php> strlen('Hellow World');
As a result, the function calculated its length for us and returned the result. As I said, when working with this function, there is one, but a very important nuance.
In the following example, I will write the same text, but only in Russian.
php> strlen('Hello world');
As a result, we get a strange result. According to the idea, we should get the number 10, but we get 19. It turns out that the strlen function does not count the number of characters in a string that we are used to, but counts the number of bytes in a string, one character in Unicode is 2 bytes, and a space is 1 byte.
So when working with this function, this nuance must be taken into account.
The next function we will use in the example is mb_strlen. The mb_strlen function takes two parameters, the first required parameter is a regular string, and the second optional parameter is an encoding. The difference between strlen and mb_strlen functions is that character count will be the same in both English and Russian. Even if the character takes several bytes, it will be counted as one byte.
php> mb_strlen("Hellow World");
php> mb_strlen("Hello world");
Thank you all, I hope that my article helped you in some way.