PHP strlen() function explained with code examples

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! ๐Ÿ‘

More PHP tutorials

See all