PHP strlen() Function
The strlen() function returns the length of a string (number of bytes).
Syntax
strlen(string $string): int
Parameters
| Parameter | Type | Description |
|---|---|---|
$string |
string | The string to measure |
Return Value
Returns the length of the string in bytes, or 0 if the string is empty.
Try It Online
Output
Click Run to execute your code
More Examples
Basic Usage
<?php
$text = "Hello, World!";
echo strlen($text); // Output: 13
?>
Password Validation
<?php
$password = "abc123";
if (strlen($password) < 8) {
echo "Password must be at least 8 characters!";
} else {
echo "Password length is acceptable.";
}
?>
Empty String Check
<?php
$empty = "";
$whitespace = " ";
echo strlen($empty); // 0
echo strlen($whitespace); // 3 (spaces are counted)
?>
Note:
strlen() counts bytes, not characters. For multibyte strings (UTF-8), use mb_strlen() instead.
Multibyte Strings
<?php
$emoji = "Hello! 👋";
echo strlen($emoji); // 11 (bytes - emoji is 4 bytes)
echo mb_strlen($emoji); // 8 (characters)
?>
Common Use Cases
- Form validation (minimum/maximum length)
- Truncating strings
- Checking if a string is empty
- Padding strings to a certain length
Related Functions
- substr() - Return part of a string
- str_replace() - Replace occurrences in a string
mb_strlen()- Get string length for multibyte strings
Enjoying these tutorials?