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 allPHP
PHP form validation basic example
Dec 22, 2022
PHP
PHP validate email address (with code examples)
Dec 22, 2022
PHP
How to redirect using PHP with code examples
Dec 22, 2022
PHP
Handling form data using PHP (GET and POST)
Dec 21, 2022
PHP
How to fix Wordpress PHP error missing MySQL extension
Dec 21, 2022