String Variables in PHP
A string is a sequence of characters enclosed within quotes.
Exam Definition: A string is a collection of characters stored inside single or double quotes.
---
Declaration Styles of String Variables
PHP supports multiple ways to declare string variables.
1. Single-Quoted Strings
- Variables are not parsed
- Faster than double quotes
$str = 'Welcome to PHP';
echo $str;
$name = 'Rohit';
echo 'Hello $name'; // Output: Hello $name
Exam Point: Single quotes treat variables as plain text.
2. Double-Quoted Strings
- Variables are parsed
- Escape sequences are supported
$name = "Rohit";
echo "Hello $name"; // Output: Hello Rohit
Escape Sequences Example
echo "Line1\nLine2";
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\" | Double quote |
\\ | Backslash |
Exam Tip: Use double quotes when variable parsing is required.
3. Concatenation of Strings
Concatenation means joining strings using dot (.) operator.
$fname = "Rohit";
$lname = "Kumar";
echo $fname . " " . $lname;
---
Heredoc Style
Heredoc is used to write multi-line strings easily.
Syntax
$str = <<<TEXT
This is a
multi-line
string
TEXT;
Heredoc with Variables
$name = "PHP";
$str = <<<DATA
Welcome to $name Programming
DATA;
echo $str;
Features
- No need for quotes
- Variables are parsed
- Useful for HTML output
Exam Definition: Heredoc allows writing multi-line strings without escape characters.
---
String Functions in PHP
PHP provides many built-in string functions for manipulation.
Commonly Used String Functions
1. strlen()
Returns string length.
echo strlen("PHP");
2. str_word_count()
Counts words in a string.
echo str_word_count("Welcome to PHP");
3. strtoupper()
Converts to uppercase.
echo strtoupper("php");
4. strtolower()
Converts to lowercase.
echo strtolower("PHP");
5. ucfirst()
Capitalizes first character.
echo ucfirst("php");
6. substr()
Extracts part of a string.
echo substr("Programming", 0, 4);
7. str_replace()
Replaces text.
echo str_replace("PHP", "Java", "PHP is easy");
8. trim()
Removes whitespace.
echo trim(" PHP ");
9. strpos()
Finds position of a word.
echo strpos("Learn PHP", "PHP");
Summary Table: String Functions
| Function | Purpose |
|---|---|
| strlen() | Length |
| strtoupper() | Uppercase |
| strtolower() | Lowercase |
| substr() | Substring |
| str_replace() | Replace |
| trim() | Remove spaces |
| strpos() | Find position |
Exam Tip: String functions simplify text manipulation.