Introduction
Strings are used in PHP to store and process text, including names, addresses, product details, messages, and other information. PHP allows you to create strings using single quotes and double quotes, combine text with variables, find string length, access individual characters, and perform many other operations. In this chapter, you will practise solved PHP questions covering string creation and basic operations with working code, sample outputs, and beginner-friendly explanations. PHP String Creation and Basic Operations Practice questions with solutions to help you understand the concepts.
Question 1: Create and Display Strings Using Single and Double Quotes
Problem Statement:
Write a PHP program to create strings using single quotes and double quotes, then display their values.
PHP Solution
<?php
$name = 'Amit';
$city = "Delhi";
$message = 'Welcome to PHP programming';
echo $name . "<br>";
echo $city . "<br>";
echo $message;
?>
Sample Output
Amit
Delhi
Welcome to PHP programming
Explanation
PHP supports both single-quoted and double-quoted strings.
- Single quotes are useful for storing simple text.
- Double quotes allow PHP to interpret variables embedded directly inside the string.
- The
echostatement displays the string. - The
.operator can join strings together.
Both types of quotes are commonly used when working with text in PHP.
Concepts Covered
- String creation
- Single quotes
- Double quotes
echostatement- Basic string output
Question 2: Display a Variable Inside a String
Problem Statement:
Create variables for an employee’s name, department, and salary. Display all three values inside a double-quoted string.
PHP Solution
<?php
$name = "Riya";
$department = "Sales";
$salary = 35000;
echo "Employee Name: $name<br>";
echo "Department: $department<br>";
echo "Monthly Salary: Rs. $salary";
?>
Sample Output
Employee Name: Riya
Department: Sales
Monthly Salary: Rs. 35000
Explanation
PHP allows variables to be inserted directly into double-quoted strings. This feature is called variable interpolation.
For example:
echo "Hello, $name";
If $name contains Riya, PHP displays Hello, Riya.
Variables are not automatically interpolated inside single-quoted strings. For simple variable insertion, double quotes are convenient.
Concepts Covered
- String interpolation
- Variables inside strings
- Double-quoted strings
- Employee information
- Output formatting
Question 3: Join Two Strings Using the Concatenation Operator
Problem Statement:
Create two variables containing a first name and a last name. Combine them into a full name using PHP’s string concatenation operator.
PHP Solution
<?php
$firstName = "Rahul";
$lastName = "Sharma";
$fullName = $firstName . " " . $lastName;
echo "Full Name: " . $fullName;
?>
Sample Output
Full Name: Rahul Sharma
Explanation
PHP uses the dot (.) operator to join strings. This operation is called string concatenation.
The statement:
$fullName = $firstName . " " . $lastName;
combines the first name, a space, and the last name.
Without the space between the two variables, the result would be RahulSharma instead of Rahul Sharma.
Concepts Covered
- String concatenation
- Dot (
.) operator - Combining variables
- Creating full names
Question 4: Append Text Using the Concatenation Assignment Operator
Problem Statement:
Create a message containing a greeting. Use the .= operator to append additional text to the same string.
PHP Solution
<?php
$message = "Welcome";
$message .= " to";
$message .= " PHP";
$message .= " programming!";
echo $message;
?>
Sample Output
Welcome to PHP programming!
Explanation
The .= operator appends text to an existing string.
For example:
$message .= " to";
is equivalent to:
$message = $message . " to";
Each statement adds more text to the current value of $message.
This operator is useful when building messages, reports, or other text gradually.
Concepts Covered
- Concatenation assignment operator
.=operator- Updating strings
- Combining multiple text values
Question 5: Find the Length of a String
Problem Statement:
Write a PHP program to find the number of bytes in a string using the strlen() function.
PHP Solution
<?php
$message = "Learn PHP";
$length = strlen($message);
echo "Message: " . $message . "<br>";
echo "String Length: " . $length;
?>
Sample Output
Message: Learn PHP
String Length: 9
Explanation
The strlen() function returns the number of bytes in a string.
The string Learn PHP contains nine characters, including the space, so its length is 9.
For ordinary English text, the byte count often matches the character count. However, some Unicode characters, including many characters used in Hindi, require multiple bytes. For those strings, use mb_strlen() with suitable multibyte string support when you need a character count.
Concepts Covered
strlen()function- String length
- Spaces in strings
- Basic string measurement
Question 6: Access Individual Characters in a String
Problem Statement:
Create a string containing the word PROGRAM. Display its first character, third character, and last character.
PHP Solution
<?php
$word = "PROGRAM";
echo "First Character: " . $word[0] . "<br>";
echo "Third Character: " . $word[2] . "<br>";
echo "Last Character: " . $word[strlen($word) - 1];
?>
Sample Output
First Character: P
Third Character: O
Last Character: M
Explanation
PHP allows you to access a character in a string using square brackets.
String positions start at index 0, not 1.
For the word PROGRAM:
| Index | Character |
|---|---|
| 0 | P |
| 1 | R |
| 2 | O |
| 3 | G |
| 4 | R |
| 5 | A |
| 6 | M |
The expression strlen($word) - 1 calculates the last index of this non-empty string.
Concepts Covered
- String indexing
- Accessing characters
- Zero-based indexes
strlen()function- String positions
Question 7: Extract Part of a String Using Substr
Problem Statement:
A company stores product codes in strings. Write a PHP program to extract the first four characters and the last three characters from the product code PRD2026XYZ.
PHP Solution
<?php
$productCode = "PRD2026XYZ";
$firstFour = substr($productCode, 0, 4);
$lastThree = substr($productCode, -3);
echo "Product Code: " . $productCode . "<br>";
echo "First Four Characters: " . $firstFour . "<br>";
echo "Last Three Characters: " . $lastThree;
?>
Sample Output
Product Code: PRD2026XYZ
First Four Characters: PRD2
Last Three Characters: XYZ
Explanation
The substr() function extracts part of a string.
Its basic syntax is:
substr(string, offset, length);
- The first argument is the original string.
- The second argument specifies where extraction begins.
- The third argument optionally specifies how many characters to extract.
In this example, substr($productCode, 0, 4) extracts four characters from the beginning. The negative offset -3 extracts the final three characters.
Concepts Covered
substr()function- String extraction
- Positive offsets
- Negative offsets
- Product-code processing
Question 8: Convert a String to Uppercase and Lowercase
Problem Statement:
Write a PHP program to display a company name in uppercase and lowercase using PHP string functions.
PHP Solution
<?php
$company = "Vsit Coding Institute";
echo "Original: " . $company . "<br>";
echo "Uppercase: " . strtoupper($company) . "<br>";
echo "Lowercase: " . strtolower($company);
?>
Sample Output
Original: Vsit Coding Institute
Uppercase: VSIT CODING INSTITUTE
Lowercase: vsit coding institute
Explanation
PHP provides functions to change the case of English letters.
strtoupper()converts lowercase English letters to uppercase.strtolower()converts uppercase English letters to lowercase.
These functions are useful when formatting labels or normalizing simple English text.
For Unicode text, such as Hindi or other non-English scripts, use the appropriate multibyte string functions when case conversion is supported.
Concepts Covered
strtoupper()strtolower()- String formatting
- Case conversion
- Company-name processing
Question 9: Remove Extra Spaces from a String
Problem Statement:
A user enters a name with extra spaces at the beginning and end. Write a PHP program to remove those spaces using the trim() function.
PHP Solution
<?php
$name = " Amit Sharma ";
echo "Original Length: " . strlen($name) . "<br>";
$cleanName = trim($name);
echo "Clean Name: " . $cleanName . "<br>";
echo "Clean Length: " . strlen($cleanName);
?>
Sample Output
Original Length: 17
Clean Name: Amit Sharma
Clean Length: 11
Explanation
The trim() function removes whitespace from the beginning and end of a string.
The original string contains three spaces before the name and three spaces after it. After trimming, the extra spaces are removed, leaving Amit Sharma.
The spaces between Amit and Sharma remain unchanged.
This function is useful when cleaning user input before processing it.
Concepts Covered
trim()function- Removing leading whitespace
- Removing trailing whitespace
- String length
- Input cleanup
Question 10: Check Whether a String Contains Specific Text
Problem Statement:
Write a PHP program to check whether a product description contains the word Laptop.
PHP Solution
<?php
$description = "Dell Laptop with 16GB RAM and 512GB SSD";
if (str_contains($description, "Laptop")) {
echo "The description contains the word Laptop.";
} else {
echo "The description does not contain the word Laptop.";
}
?>
Sample Output
The description contains the word Laptop.
Explanation
The str_contains() function checks whether one string contains another string.
In this example, PHP checks whether $description contains the text Laptop. Because the word exists in the description, the condition is true and the first message is displayed.
Important: str_contains() is available in PHP 8.0 and later. The comparison is case-sensitive, so Laptop and laptop are treated as different strings.
Concepts Covered
str_contains()function- Searching within strings
if-elsestatements- Case-sensitive matching
- Product-description processing
Key Takeaways
- PHP strings store text such as names, messages, addresses, and product descriptions.
- Strings can be created using single quotes or double quotes.
- Double-quoted strings can interpolate variables.
- The dot (
.) operator joins strings together. - The
.=operator appends text to an existing string. strlen()returns the number of bytes in a string.- String indexes start at
0. substr()extracts part of a string.strtoupper()andstrtolower()change the case of English letters.trim()removes whitespace from the beginning and end of a string.str_contains()checks whether one string contains another and requires PHP 8.0 or later.- Multibyte text may require functions such as
mb_strlen()for accurate character counting.
Frequently Asked Questions (FAQs)
1. What is a string in PHP?
A string is a data type used to store text, such as a person’s name, a message, an address, or a product description.
2. How can I create a string in PHP?
You can create a string using single or double quotes.
$name = 'Amit';
$message = "Welcome to PHP";
3. What is the difference between single and double quotes in PHP?
Double-quoted strings support variable interpolation and interpret certain escape sequences. Single-quoted strings generally treat their contents literally, except for specific escape sequences such as \\ and \'.
4. What is string concatenation in PHP?
String concatenation means joining two or more strings. PHP uses the dot (.) operator to combine them.
echo "Hello " . "World";
Output: Hello World
5. What does the strlen() function do?
The strlen() function returns the number of bytes in a string. For ordinary English text, this usually matches the number of characters.
6. How can I access a character from a string?
You can use square brackets and a zero-based index.
$word = "PHP";
echo $word[0];
Output: P
7. What is the purpose of the substr() function?
The substr() function extracts a portion of a string using a starting offset and an optional length.
8. How can I convert a string to uppercase?
Use strtoupper().
echo strtoupper("hello php");
Output: HELLO PHP
9. How can I remove extra spaces from a string?
Use trim() to remove whitespace from the beginning and end of a string. It does not remove spaces between words.
10. How can I check whether a string contains a word in PHP?
In PHP 8.0 or later, you can use str_contains().
echo str_contains("Learn PHP", "PHP") ? "Found" : "Not Found";
Output: Found
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
