CodeBlanks Logo Icon CodeBlanks

Length with strlen()

PHP course · Beginner · Lesson 31/116

Learn the character length of a string with strlen().

Length with strlen()

In PHP, the strlen() function tells you how many characters a string has. The call strlen("Hello") returns 5 because "Hello" has five characters.

When you print the result with echo you see 5 on the screen: echo strlen("Hello");. This function is useful for checking whether a string is empty or making decisions based on its length.

Bytes or characters?

strlen() actually counts the bytes of a string. Non-ASCII characters take more than one byte in UTF-8, so strlen("çay") may return 4 because the letter ç uses two bytes. This can be surprising.

For the true character count, use mb_strlen(). mb_strlen("çay") returns 3. In Turkish text and multilingual content, prefer mb_strlen(). For ASCII text, both functions return the same value.

Exercise Print the string length

Assign the string "Ayşe" to $name. Then print its length with echo strlen($name);. The output is 5 because the letter ş takes two bytes in UTF-8.

Show example solution
Write $name = "Ayşe"; and print the length with strlen.
Example solution:
<?php
$name = "Ayşe";
echo strlen($name);

Test yourself

  1. What is the output of echo strlen("PHP");?

    echo strlen("PHP");
    • 3
    • 2
    • 4
    • It errors
    Show answer

    3 — Correct. "PHP" has three characters; strlen returns 3.

  2. Complete the strlen call

    $name = 'Alex';
    echo ____($name);
    Show answer
    $name = 'Alex';
    echo strlen($name);
  3. Match each function to its job

    strlen
    Counts bytes
    mb_strlen
    Counts characters
    echo
    Prints to screen

All lessons in Beginner