PHP strlen() function
The strlen()
function in PHP is used to calculate the length of a string, meaning it counts the number of characters in the string, including spaces and special characters.
Syntax:
- string: The input string whose length is to be determined.
Example 1: Basic Usage
Output:
Explanation: The string "Hello World!"
has 12 characters, including the space and the exclamation mark.
Example 2: Counting Spaces and Special Characters
Output:
Explanation: The string contains spaces before and after the text, and strlen()
counts those spaces along with the text and special characters. Hence, the total length is 25.
Example 3: Empty String
Output:
Explanation: An empty string has no characters, so the length is 0.
Example 4: Special Characters
Output:
Explanation: Although "Hello 🌍!"
visually looks like 8 characters, strlen()
counts the special emoji (🌍
) as multiple bytes (depending on encoding), resulting in a total length of 10.
The strlen()
function is simple but essential for tasks like validation (checking if input is the correct length) or limiting content display.