Introduction
PHP provides several ways to find the length of a string and access individual characters. These operations are useful when validating usernames, checking passwords, processing employee data, and working with text. In this chapter, you will practice using strlen(), string indexes, loops, and other basic techniques through solved PHP questions with working code and sample outputs. PHP String Length and Character Access practice question with solutions to help you understand the concepts.
Question 1: Find the Length of a String Using strlen()
Problem Statement
Write a PHP program to find the number of characters in the string "PHP" using the strlen() function.
PHP Solution
<?php
$text = "PHP";
$length = strlen($text);
echo "String: " . $text . "<br>";
echo "Length: " . $length;
?>
Sample Output
String: PHP
Length: 3
Explanation
The strlen() function returns the length of a string in bytes. For ordinary English letters and spaces, each character occupies one byte.
Here, "PHP" contains three characters, so strlen($text) returns 3.
Concepts Covered
- PHP strings
strlen()function- String length calculation
- Variables and output
Question 2: Calculate the Length of an Employee’s Name
Problem Statement
An employee database stores each employee’s name. Write a PHP program to calculate the length of the employee name "Amit Sharma".
PHP Solution
<?php
$employeeName = "Amit Sharma";
$nameLength = strlen($employeeName);
echo "Employee Name: " . $employeeName . "<br>";
echo "Name Length: " . $nameLength;
?>
Sample Output
Employee Name: Amit Sharma
Name Length: 11
Explanation
The name "Amit Sharma" contains four letters in Amit, one space, and six letters in Sharma.
Therefore, the total length is:
4 + 1 + 6 = 11
The strlen() function includes spaces when calculating the length of a string.
Concepts Covered
- Calculating name length
- Using
strlen()with variables - Counting spaces
- Employee data processing
Question 3: Access the First Character of a String
Problem Statement
Write a PHP program to display the first character of the string "CODING" using string indexing.
PHP Solution
<?php
$text = "CODING";
$firstCharacter = $text[0];
echo "String: " . $text . "<br>";
echo "First Character: " . $firstCharacter;
?>
Sample Output
String: CODING
First Character: C
Explanation
PHP allows you to access an individual character using square brackets [].
String indexing starts at 0, not 1.
For the string "CODING":
| Index | Character |
|---|---|
| 0 | C |
| 1 | O |
| 2 | D |
| 3 | I |
| 4 | N |
| 5 | G |
Therefore, $text[0] returns C.
Concepts Covered
- String indexing
- Accessing individual characters
- Zero-based indexing
- Square bracket notation
Question 4: Access the Last Character of a String
Problem Statement
Write a PHP program to display the last character of the string "PROGRAMMING" without manually counting its characters.
PHP Solution
<?php
$text = "PROGRAMMING";
$length = strlen($text);
$lastCharacter = $text[$length - 1];
echo "String: " . $text . "<br>";
echo "Length: " . $length . "<br>";
echo "Last Character: " . $lastCharacter;
?>
Sample Output
String: PROGRAMMING
Length: 11
Last Character: G
Explanation
PHP uses zero-based string indexing, so the last character is located at the string’s length minus one.
The expression:
$text[strlen($text) - 1]
calculates the last character’s index automatically.
For "PROGRAMMING", the length is 11, so the last character is at index 10.
This technique is useful when working with strings of different lengths.
Concepts Covered
strlen()function- Last-character access
- Zero-based indexing
- Dynamic string processing
Question 5: Access a Character at a Specific Position
Problem Statement
A company stores product codes as strings. Write a PHP program to access the character at index 3 in the product code "COMPUTER".
PHP Solution
<?php
$productCode = "COMPUTER";
$character = $productCode[3];
echo "Product Code: " . $productCode . "<br>";
echo "Character at Index 3: " . $character;
?>
Sample Output
Product Code: COMPUTER
Character at Index 3: P
Explanation
The string "COMPUTER" uses zero-based indexing.
| Index | Character |
|---|---|
| 0 | C |
| 1 | O |
| 2 | M |
| 3 | P |
| 4 | U |
| 5 | T |
| 6 | E |
| 7 | R |
The expression $productCode[3] returns P.
Remember that index 3 refers to the fourth character because indexing starts at zero.
Concepts Covered
- Accessing characters by index
- Product code processing
- String positions
- Zero-based indexing
Question 6: Display Every Character of a String Using a Loop
Problem Statement
Write a PHP program to display every character of the string "HELLO" on a separate line using a for loop.
PHP Solution
<?php
$text = "HELLO";
$length = strlen($text);
for ($i = 0; $i < $length; $i++) {
echo $text[$i] . "<br>";
}
?>
Sample Output
H
E
L
L
O
Explanation
The strlen() function calculates the string length, which is 5.
The for loop starts at index 0 and continues while $i is less than 5.
During each iteration, $text[$i] accesses the character at the current index.
The loop displays all five characters individually.
Concepts Covered
forloopstrlen()function- String indexing
- Character-by-character processing
Question 7: Count the Number of Characters in a Sentence
Problem Statement
Write a PHP program to calculate the length of the sentence "Learn PHP" and display the result.
PHP Solution
<?php
$sentence = "Learn PHP";
$length = strlen($sentence);
echo "Sentence: " . $sentence . "<br>";
echo "Total Length: " . $length;
?>
Sample Output
Sentence: Learn PHP
Total Length: 9
Explanation
The sentence contains:
Learn: 5 characters- Space: 1 character
PHP: 3 characters
The total length is 5 + 1 + 3 = 9.
The strlen() function counts the space as well as the letters.
Important: strlen() measures bytes, not necessarily the number of visible characters. For ordinary English text, these counts usually match. For UTF-8 text containing characters such as many Hindi letters or emojis, one visible character can occupy multiple bytes.
Concepts Covered
- Sentence length
- Counting spaces
strlen()function- Bytes versus characters
Question 8: Compare String Length Before and After trim()
Problem Statement
A user enters a name with unnecessary spaces at the beginning and end. Write a PHP program to display the string length before and after removing those spaces using trim().
PHP Solution
<?php
$name = " Rahul ";
$originalLength = strlen($name);
$cleanName = trim($name);
$cleanLength = strlen($cleanName);
echo "Original Length: " . $originalLength . "<br>";
echo "Clean Name: " . $cleanName . "<br>";
echo "Length After trim(): " . $cleanLength;
?>
Sample Output
Original Length: 11
Clean Name: Rahul
Length After trim(): 5
Explanation
The original string contains five letters and six extra spaces: three before the name and three after it.
Therefore, its original length is 11.
The trim() function removes whitespace from the beginning and end of a string. After trimming, only "Rahul" remains, giving a length of 5.
Notice that trim() does not remove spaces from the middle of a string.
Concepts Covered
trim()functionstrlen()function- Removing extra spaces
- Cleaning user input
Question 9: Validate a Username Using String Length
Problem Statement
A website requires usernames to contain between 5 and 12 characters. Write a PHP program to check whether the username "rahul123" meets this requirement.
PHP Solution
<?php
$username = "rahul123";
$length = strlen($username);
echo "Username: " . $username . "<br>";
echo "Username Length: " . $length . "<br>";
if ($length >= 5 && $length <= 12) {
echo "Username is valid.";
} else {
echo "Username is invalid.";
}
?>
Sample Output
Username: rahul123
Username Length: 8
Username is valid.
Explanation
The username "rahul123" contains eight characters.
The condition checks two requirements:
$length >= 5: the username must contain at least five characters.$length <= 12: the username must contain no more than twelve characters.
The && operator requires both conditions to be true.
Since 8 falls between 5 and 12, the program displays "Username is valid."
This is a basic length check, not a complete username validation system. A real website should also check permitted characters and enforce its rules on the server.
Concepts Covered
- Username validation
strlen()functionif-elsestatement- Logical AND operator
- Input validation
Question 10: Count Vowels in a String Using Character Access
Problem Statement
Write a PHP program to count the vowels in the string "education" by accessing each character using a loop.
PHP Solution
<?php
$text = "education";
$length = strlen($text);
$vowelCount = 0;
for ($i = 0; $i < $length; $i++) {
$character = strtolower($text[$i]);
if (
$character == "a" ||
$character == "e" ||
$character == "i" ||
$character == "o" ||
$character == "u"
) {
$vowelCount++;
}
}
echo "String: " . $text . "<br>";
echo "Number of Vowels: " . $vowelCount;
?>
Sample Output
String: education
Number of Vowels: 5
Explanation
The program checks every character in "education".
The vowels are:
euaio
Whenever a vowel is found, $vowelCount++ increases the counter by one.
After checking all nine characters, the final vowel count is 5.
The strtolower() function converts each character to lowercase before checking it, making the vowel comparison work for uppercase and lowercase English letters.
Concepts Covered
- String indexing
strlen()functionforloopstrtolower()function- Conditional statements
- Counting characters that match a condition
Key Takeaways
- The
strlen()function returns the length of a string in bytes. - PHP string indexes begin at
0. - Use
$text[0]to access the first character of a non-empty string. - Use
$text[strlen($text) - 1]to access the last character of a non-empty string. - Use
$text[$i]inside a loop to access characters individually. - Spaces are included when calculating string length.
- The
trim()function removes whitespace from the beginning and end of a string. - String length can be used for basic username and input validation.
- Loops and string indexing can be combined to count vowels or process individual characters.
- For UTF-8 text containing multibyte characters,
strlen()and ordinary string indexing do not necessarily correspond to visible characters.
Frequently Asked Questions (FAQs)
1. What is the strlen() function in PHP?
The strlen() function returns the length of a string in bytes. For ordinary English text, the result generally matches the number of characters.
<?php
echo strlen("Hello");
?>
Output:
5
2. How do you find the length of a string in PHP?
Pass the string or a string variable to strlen().
<?php
$text = "Programming";
echo strlen($text);
?>
Output:
11
3. How do you access the first character of a string in PHP?
Use index 0 inside square brackets.
<?php
$text = "Python";
echo $text[0];
?>
Output:
P
4. How do you access the last character of a string in PHP?
For a non-empty string, use the string length minus one as the index.
<?php
$text = "Hello";
echo $text[strlen($text) - 1];
?>
Output:
o
Make sure the string is not empty before accessing its last character.
5. Does PHP string indexing start from 0 or 1?
PHP string indexing starts at 0. The first character is at index 0, the second at index 1, and the third at index 2.
6. Does strlen() count spaces in PHP?
Yes. Spaces are included in the string length.
<?php
echo strlen("Hi PHP");
?>
Output:
6
7. How can you display every character in a PHP string?
Use a for loop with strlen() and access each character using square brackets.
<?php
$text = "CAT";
for ($i = 0; $i < strlen($text); $i++) {
echo $text[$i] . "<br>";
}
?>
Output:
C
A
T
For larger strings, calculating the length once before the loop can avoid repeated function calls.
8. What happens if you access an index outside a string’s length?
Accessing an index that does not exist can produce an undefined string offset warning or other unexpected behavior, depending on the PHP version and context. Check the string length before accessing an index.
9. What is the difference between strlen() and trim()?
strlen() measures the string’s length in bytes, while trim() returns a string with whitespace removed from its beginning and end. They perform different tasks, but you can combine them to calculate the length after trimming.
10. Does strlen() count Hindi characters and emojis correctly?
Not necessarily. strlen() counts bytes, so a visible character encoded using multiple UTF-8 bytes contributes more than one to the result. For Unicode-aware character counts, consider mb_strlen() when the PHP mbstring extension is available.
For example:
<?php
$text = "Hello";
echo mb_strlen($text, "UTF-8");
?>
Output:
5
This example uses English text, but mb_strlen() can also count Unicode characters more appropriately than strlen().
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
