The strlen()
function is used to get the length of a string in PHP.
The function accepts a string
and returns an int
representing the number of bytes in that string
:
strlen(string $string): int
Here are some examples of using the strlen()
function:
<?php
echo strlen("Hello!"); // 6
// ๐ white spaces will be counted in the length
echo strlen(" Nat han "); // 9
// ๐ empty string returns 0
echo strlen(""); // 0
// ๐ when passing boolean,
// returns the number representation of the value
echo strlen(true); // 1
echo strlen(false); // 0
// ๐ Passing integers
// Return the lenght of the integers
echo strlen(777); // 3
echo strlen(10239); // 5
?>
The strlen()
function returns the number of bytes rather than the number of characters in a string.
This distinction is important when you are trying to count the length of UTF-8 encoded characters.
For example, the following Japanese language โใใใซใกใฏโ has five characters, but strlen()
returns 15
:
echo strlen("ใใใซใกใฏ"); // 15
echo mb_strlen("ใใใซใกใฏ"); // 5
The mb_strlen()
function is an upgraded strlen()
functio that takes the string encoding into account. It will count a multi-byte character as 1
.
Now youโve learned how the strlen()
function works in PHP. Nice! ๐