0
0
PHPprogramming~5 mins

String length and counting in PHP

Choose your learning style9 modes available
Introduction

We use string length and counting to find out how many characters are in a word or sentence. This helps us check or control text size.

Checking if a password is long enough before saving it.
Counting how many letters are in a user's name.
Finding out how many characters a message has before sending it.
Validating input length in a form to avoid errors.
Syntax
PHP
$length = strlen($string);

strlen() is a built-in PHP function that returns the number of characters in a string.

The count includes letters, numbers, spaces, and special characters.

Examples
This counts the letters in "Hello" and prints 5.
PHP
$text = "Hello";
$length = strlen($text);
echo $length;
This counts all characters including space and exclamation mark, printing 9.
PHP
$sentence = "Hi there!";
echo strlen($sentence);
Counting an empty string returns 0.
PHP
$empty = "";
echo strlen($empty);
Sample Program

This program counts how many characters are in the string stored in $userInput and prints a friendly message.

PHP
<?php
// Example: Count characters in a user input string
$userInput = "Learn PHP!";
$length = strlen($userInput);
echo "The string '" . $userInput . "' has " . $length . " characters.";
?>
OutputSuccess
Important Notes

Remember, strlen() counts all characters including spaces and punctuation.

For multibyte characters (like emojis or some foreign letters), strlen() may not count as expected. Use mb_strlen() for those cases.

Summary

strlen() tells you how many characters are in a string.

It counts everything: letters, spaces, and symbols.

Use it to check or control text size in your programs.