To find out how long a string is, use strlen().
<?php
$password = "secret123";
echo strlen($password);
9
Spaces and punctuation count too.
<?php
echo strlen("Hello, world!");
13
Use it to validate input
<?php
$username = "al";
if (strlen($username) < 3) {
echo "Username must be at least 3 characters.";
}
Username must be at least 3 characters.
strlen counts bytes
strlen() counts bytes, not characters. For English letters, they are the same. For characters outside basic English, they are not.
<?php
echo strlen("naive") . "\n";
echo strlen("naïve") . "\n";
echo mb_strlen("naïve");
5
6
5
mb_strlen() counts real characters. Use it whenever the text could contain accents, Hindi, emoji or other non-English characters. See Multibyte Strings.
Count words
<?php
$text = "PHP is easy to learn";
echo str_word_count($text);
5
str_word_count() is fine for English text. For other languages, split the text yourself.
Empty strings
<?php
var_dump(strlen("") === 0);
var_dump("" === "");
bool(true)
bool(true)
Do not use strlen() to check for a missing value
null or a missing variable is not an empty string. Check with isset() first, then with === "" or strlen().Exercise: a tweet counter
Print how many characters are left in a 100-character limit for the text "Learning PHP step by step".
Show a possible solution
<?php
$text = "Learning PHP step by step";
$limit = 100;
echo "Characters left: " . ($limit - mb_strlen($text));
Characters left: 75