How to Find Length of String in PHP: Simple Guide
In PHP, you can find the length of a string using the
strlen() function. It returns the number of characters in the string, including spaces and special characters.Syntax
The strlen() function takes one argument, which is the string you want to measure. It returns an integer representing the number of characters in that string.
- strlen(string $string): int
$string: The input string whose length you want to find.- Returns the length as an integer.
php
strlen(string $string): intExample
This example shows how to use strlen() to find the length of different strings, including spaces and special characters.
php
<?php $string1 = "Hello, world!"; $string2 = " PHP "; $string3 = "12345"; echo strlen($string1) . "\n"; // Outputs 13 echo strlen($string2) . "\n"; // Outputs 5 (spaces count) echo strlen($string3) . "\n"; // Outputs 5 ?>
Output
13
5
5
Common Pitfalls
One common mistake is expecting strlen() to count characters correctly for multibyte (e.g., UTF-8) strings. strlen() counts bytes, not characters, so it may give unexpected results for non-ASCII characters.
For multibyte strings, use mb_strlen() instead.
php
<?php // Wrong for multibyte strings $string = "こんにちは"; // Japanese greeting echo strlen($string) . "\n"; // Outputs 15 (bytes, not characters) // Correct way for multibyte strings echo mb_strlen($string, 'UTF-8') . "\n"; // Outputs 5 (characters) ?>
Output
15
5
Quick Reference
| Function | Purpose | Notes |
|---|---|---|
| strlen() | Returns length in bytes | Use for ASCII or single-byte strings |
| mb_strlen() | Returns length in characters | Use for multibyte strings like UTF-8 |
Key Takeaways
Use
strlen() to get the length of a string in PHP for simple ASCII text.Remember
strlen() counts bytes, not characters, which can cause issues with multibyte text.Use
mb_strlen() with the correct encoding for strings containing special or multibyte characters.Spaces and special characters are counted by
strlen() as part of the string length.