What is a String in PHP?
Definition
In PHP, a String is a sequence of characters, where a character is the same as a byte. This means PHP has a set of 256 possible characters and provides native support for binary data (strings are binary-safe).
In PHP, there is no artificial length limit on strings. A string can be as large as the available PHP memory allows (configured in memory_limit).
PHP gives you 4 distinct syntaxes: Single Quoted, Double Quoted, Heredoc, and Nowdoc.
<?php
// Strings in PHP can store text, numbers, symbols, and binary data
$name = "Shubh";
$greeting = 'Welcome to PHP Mastery!';
$price = '$49.99';
$multiline = "Line 1\nLine 2";
echo $greeting; // Outputs: Welcome to PHP Mastery!
?>
Single-Quoted Strings (' ')
Definition & Characteristics
A Single-Quoted String is the simplest and purest way to specify text in PHP. It is enclosed within single quotation marks ('...').
- Literal Evaluation: PHP treats almost everything inside single quotes completely literally.
- No Variable Parsing: Variables like
$nameare NOT expanded. They print literally as$name. - Only 2 Escape Sequences: Only
\'(to escape a literal single quote) and\\(to escape a backslash) are supported. Escape sequences like\n(newline) or\t(tab) will output verbatim as text!
Syntax & Example
<?php
$author = 'Shubh';
// 1. Literal text
$message = 'Hello world, welcome to PHP!';
// 2. Variables are NOT parsed
$quote = 'Author is $author';
// Output: Author is $author
// 3. Escape sequences are literal (except \' and \\)
$path = 'C:\\xampp\\htdocs'; // Output: C:\xampp\htdocs
$escapedQuote = 'It\'s a wonderful day!'; // Output: It's a wonderful day!
$newline = 'Line 1\nLine 2'; // Output: Line 1\nLine 2 (does NOT create a newline!)
echo $quote . "\n";
echo $escapedQuote . "\n";
echo $path . "\n";
echo $newline;
?>
Double-Quoted Strings (" ")
Definition & Characteristics
A Double-Quoted String is enclosed within double quotation marks ("..."). It provides dynamic string processing capabilities, enabling variable interpolation and rich escape sequence interpretation.
- Variable Interpolation / Parsing: Variable names starting with
$will be replaced with their evaluated value. - Complex (Curly) Syntax: Allows embedding complex expressions, object properties, or array keys using
{$variable}or${variable}(e.g.,"User: {$user['name']}"). - Rich Escape Sequences: Supports
\n(linefeed),\r(carriage return),\t(tab),\$(dollar sign),\"(double quote),\x[0-9A-Fa-f]{1,2}(hex), and Unicode\u{...}.
Escape Sequences Supported in Double Quotes:
| Sequence | Meaning | Example | Rendered Result |
|---|---|---|---|
\n | Linefeed / Newline | "Hello\nWorld" | 2 lines |
\r | Carriage Return | "Hello\rWorld" | CR control char |
\t | Horizontal Tab | "Name:\tShubh" | Tabulated spacing |
\\ | Backslash | "C:\\PHP" | C:\PHP |
\$ | Literal Dollar sign | "Cost: \$50" | Cost: $50 |
\" | Literal Double Quote | "He said \"Hi!\"" | He said "Hi!" |
\u{1F600} | Unicode Codepoint | "Smile: \u{1F600}" | Smile: 😀 |
Syntax & Example
<?php
$name = 'Shubh';
$course = 'PHP Mastery';
$user = ['role' => 'Admin', 'xp' => 500];
// 1. Simple variable interpolation
echo "Hello, $name! Welcome to $course.\n";
// 2. Complex / Curly syntax for arrays and disambiguation
echo "Role: {$user['role']} (XP: {$user['xp']})\n";
echo "He drank 3 {$juice}glasses.\n"; // prevents ambiguity
// 3. Escape characters
echo "Special Offer: \"Buy 1 Get 1 Free\" for only \$19.99!\n";
echo "Tabbed\tColumns\tData\n";
echo "Unicode support: \u{1F680} Rocket launched!";
?>
Heredoc String Syntax (<<<IDENTIFIER)
Definition & Characteristics
Heredoc syntax provides a clean way to define multiline strings with full variable interpolation and escape sequence processing, without needing to escape quotes (both single and double quotes can be used freely).
- Behaves like Double Quotes: Variables (
$var,{$var}) are parsed and evaluated. - No Quote Escaping: You can embed single quotes (
') and double quotes (") without backslashes. - Perfect For: Multiline HTML templates, SQL queries, JSON payloads, and email templates.
- PHP 7.3+ Flexible Indentation: The closing delimiter can be indented with spaces/tabs matching the body indentation.
Syntax Structure
<<<DELIMITER
... multiline content with $variables and "quotes" ...
DELIMITER;
Complete Example
<?php
$studentName = "Shubh";
$courseName = "Backend Web Development";
$score = 98;
// Defining a multiline HTML email template with Heredoc
$htmlEmail = <<<HTML
<div class="card">
<h2>Certificate of Completion</h2>
<p>Congratulations, <strong>$studentName</strong>!</p>
<p>You scored <span class="badge">{$score}%</span> in <em>$courseName</em>.</p>
<button onclick="alert('Welcome to PHP!')">Download Certificate</button>
</div>
HTML;
echo $htmlEmail;
?>
Nowdoc String Syntax (<<<'IDENTIFIER')
Definition & Characteristics
A Nowdoc is to Heredoc what a single-quoted string is to a double-quoted string. It is specified similarly to a Heredoc, but the opening identifier is enclosed in single quotes (e.g. <<<'EOT').
- Behaves like Single Quotes: No variable parsing and no escape sequence evaluation happens.
- Raw Code & Scripts: Ideal for embedding raw PHP scripts, JavaScript code, regex patterns, bash scripts, or SQL code where
$symbols should remain untouched. - Zero Escaping Needed: No need to escape
$,\,", or'.
Syntax Structure
<<<'DELIMITER'
... raw multiline content, $variables and \n are NOT evaluated ...
DELIMITER;
Complete Example
<?php
$name = "Shubh";
// Notice the single quotes around 'RAW_CODE'
$rawPhpCode = <<<'RAW_CODE'
<?php
// In Nowdoc, $name and $count are NOT evaluated!
$name = "Guest";
$count = 10;
for ($i = 0; $i < $count; $i++) {
echo "Iteration $i: $name\n";
}
?>
RAW_CODE;
echo $rawPhpCode;
?>
What's the Difference? Side-by-Side Analysis
Comparison 1
Single-Quoted ('...') vs Double-Quoted ("...")
| Feature | Single-Quoted ('...') |
Double-Quoted ("...") |
|---|---|---|
| Variable Interpolation | No (Prints $var literally) |
Yes (Replaces $var with value) |
| Escape Sequences | Supports only \' and \\ |
Supports \n, \r, \t, \$, \", \u{...}, etc. |
| Parsing Overhead | Faster execution (PHP doesn't inspect for variables) | Slightly more parsing overhead to scan for variables and escapes |
| Readability for HTML | Great when HTML attributes use double quotes: '<a href="link">' |
Requires escaping: "<a href=\"link\">" |
| Best Use Case | Static text, dictionary keys, constant strings, raw SQL queries | Dynamic messages, formatted strings, templated text with variables |
<?php
$fruit = "Apple";
echo 'I love $fruit\n';
// Output: I love $fruit\n
?>
<?php
$fruit = "Apple";
echo "I love $fruit\n";
// Output: I love Apple
// (with actual newline)
?>
Comparison 2
Heredoc (<<<EOT) vs Nowdoc (<<<'EOT')
| Feature | Heredoc (<<<EOT) |
Nowdoc (<<<'EOT') |
|---|---|---|
| Syntax Identifier | Unquoted: <<<EOT (or double quoted <<<"EOT") |
Single-quoted: <<<'EOT' |
| Behavior Equivalent | Equivalent to Double Quotes (multiline) | Equivalent to Single Quotes (multiline) |
| Variable Interpolation | Enabled ($name is replaced) |
Disabled ($name is treated as literal) |
| Escape Sequences | Evaluated (\n, \t, \$) |
Literal text (\n remains \n) |
| Best Use Case | Dynamic HTML templates, dynamic SQL queries, custom emails with user data | Embedding raw scripts (PHP, JS, Shell), Regex patterns, static config files |
<?php
$table = "users";
$role = "admin";
$sql = <<<SQL
SELECT id, email
FROM {$table}
WHERE role = '$role';
SQL;
// Variables $table & $role are populated!
?>
<?php
$js = <<<'JAVASCRIPT'
// jQuery / JS code with $ untouched
$(document).ready(function() {
$('#btn').click(function() {
console.log("Clicked!");
});
});
JAVASCRIPT;
// $ is not treated as a PHP variable!
?>
Decomposing & Joining Strings: explode() & implode()
In PHP, string decomposition is the process of breaking a single structured text string into discrete array elements using a delimiter. Conversely, string composition reassembles array elements back into a unified string.
Definition: explode() splits a string by a specified string separator and returns an indexed array of substrings.
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array",", "/", " "). Cannot be empty "".- Positive ($limit > 0): Returns up to
$limitelements. The final element contains the remainder of the string. - Negative ($limit < 0): Returns all elements except the last
-$limitelements.
<?php
// 1. Basic Decomposition (Comma Separated CSV)
$data = "PHP,MySQL,HTML,CSS,JavaScript";
$skills = explode(",", $data);
print_r($skills);
// 2. Using Positive Limit ($limit = 3)
// Only 3 elements returned; the 3rd element holds the rest!
$url = "user/profile/settings/security";
$parts = explode("/", $url, 3);
print_r($parts);
// Output: ['user', 'profile', 'settings/security']
// 3. Using Negative Limit ($limit = -1)
// Discards the last element
$filename = "report_q1_2026.final.pdf";
$clean = explode(".", $filename, -1);
print_r($clean);
// Output: ['report_q1_2026', 'final']
?>
Definition: implode() joins all array elements into a single continuous string using a "glue" separator string between each item.
implode(string $separator = "", array $array): string", ", " -> ", "-"). Defaults to empty string "".join() is an exact built-in alias of implode() with identical behavior and zero performance overhead.<?php
// 1. Basic Composition with glue
$techStack = ["PHP 8", "Laravel", "MySQL", "Tailwind"];
$joined = implode(" -> ", $techStack);
echo $joined . "\n\n";
// 2. Real-World: Dynamic SQL IN Clause
$allowedRoles = ["admin", "editor", "moderator"];
$sqlRoles = "'" . implode("', '", $allowedRoles) . "'";
$query = "SELECT * FROM users WHERE role IN ($sqlRoles);";
echo $query . "\n\n";
// 3. Real-World: Building HTML Badges
$tags = ["Web", "Backend", "Security"];
$htmlBadges = '' . implode(' ', $tags) . '';
echo $htmlBadges;
?>
Additional String Decomposing Functions in PHP
$str = "SHUBH";
$chars = str_split($str, 1);
// ['S', 'H', 'U', 'B', 'H']
$chunks = str_split("12345678", 2);
// ['12', '34', '56', '78']
$path = "https://example.com/api/v1/users";
$token = strtok($path, "/:");
while ($token !== false) {
echo $token . " ";
$token = strtok("/:");
}
// Outputs: https example.com api v1 users
Comparison: explode() vs implode() vs str_split()
| Function | Input Type | Output Type | Mechanism | Primary Use Case |
|---|---|---|---|---|
explode() |
string |
array |
Splits string by a delimiter boundary pattern | Parsing CSV, splitting paths, URLs, query parameters |
implode() |
array |
string |
Glues array items together into one string | Building SQL queries, generating CSVs, creating readable lists |
str_split() |
string |
array |
Splits string into fixed character lengths | Converting strings to char arrays, credit card formatting |
Regular Expressions in PHP & POSIX (ereg)
A Regular Expression (RegEx) is a sequence of characters that forms a search pattern. It is used for validating inputs (e.g. emails, phone numbers), searching through text, parsing data, and executing complex string substitutions.
Two Regular Expression Engines in PHP History
POSIX (Portable Operating System Interface) is an IEEE standard for Unix compatibility. POSIX expressions do not require wrapping pattern delimiters (no /.../).
Used via ereg(), eregi(), ereg_replace(), and split(). Deprecated in PHP 5.3 and removed in PHP 7 in favor of PCRE, but fundamental for computer science curricula, examinations, and legacy codebases.
PCRE is the modern, highly optimized standard used in modern PHP 7 and PHP 8+. It requires enclosing delimiters such as /pattern/modifiers.
Used via preg_match(), preg_match_all(), preg_replace(), and preg_split(). Provides superior speed, lookahead/lookbehind assertions, and rich Unicode support.
The POSIX (ereg) Function Family
PHP provided 6 core built-in POSIX functions for matching, replacing, and splitting strings:
| POSIX Function | Syntax | Sensitivity | Description |
|---|---|---|---|
ereg() |
ereg(string $pattern, string $string, array &$regs = null): int|false |
Case-Sensitive | Matches a POSIX regular expression against a string. Fills $regs with captured groups. |
eregi() |
eregi(string $pattern, string $string, array &$regs = null): int|false |
Case-Insensitive | Same as ereg(), but ignores uppercase/lowercase distinctions (e.g. abc matches ABC). |
ereg_replace() |
ereg_replace(string $pattern, string $replacement, string $string): string |
Case-Sensitive | Replaces occurrences of $pattern with $replacement in $string. |
eregi_replace() |
eregi_replace(string $pattern, string $replacement, string $string): string |
Case-Insensitive | Case-insensitive pattern replacement. |
split() |
split(string $pattern, string $string, int $limit = -1): array |
Case-Sensitive | Splits string into array by POSIX regular expression pattern boundaries. |
spliti() |
spliti(string $pattern, string $string, int $limit = -1): array |
Case-Insensitive | Case-insensitive version of POSIX split(). |
Core POSIX / ereg Metacharacters Explained
Metacharacters are special symbols with dedicated algorithmic meanings in regular expressions:
| Symbol | Name | Meaning & Definition | Syntax / Pattern | Matching Example |
|---|---|---|---|---|
^ |
Caret (Start Anchor) | Asserts the beginning of the string. Pattern must appear right at the start. | ^PHP |
Matches "PHP 8"Fails "Learn PHP" |
$ |
Dollar (End Anchor) | Asserts the end of the string. Pattern must appear right at the end. | \.pdf$ |
Matches "report.pdf"Fails "report.pdf.zip" |
. |
Dot / Period (Wildcard) | Matches any single character (letter, digit, symbol, space) except newline \n. |
c.t |
Matches "cat", "cot", "c9t", "c#t" |
\ |
Backslash (Escape) | Escapes the special meaning of a metacharacter to treat it as a literal symbol. | \$[0-9]+ |
Matches "$100" (literal dollar symbol followed by digits) |
[] |
Square Brackets (Character Set) | Matches any single character from the enclosed set or range. | [0-9], [a-zA-Z] |
[aeiou] matches any single vowel; [0-9] matches single digit. |
[^] |
Negated Character Set | Matches any single character NOT inside the bracket set. | [^0-9] |
Matches "a", "#", " " (any non-digit character) |
() |
Parentheses (Grouping / Capturing) | Groups subpatterns together and captures the matched substring into $regs array. |
([a-z]+)@([a-z]+) |
Captures username in $regs[1] and host in $regs[2] |
| |
Pipe (Alternation / Logical OR) | Matches the pattern before OR after the pipe. | (cat|dog|bird) |
Matches either "cat", "dog", or "bird" |
POSIX Repetition Quantifiers:
| Quantifier | Meaning | Example | Match Result |
|---|---|---|---|
* | 0 or more times (optional, repeatable) | ab*c | Matches "ac", "abc", "abbbbc" |
+ | 1 or more times (at least once) | ab+c | Matches "abc", "abbc" (Fails "ac") |
? | 0 or 1 time (optional single occurrence) | https? | Matches "http" and "https" |
{n} | Exactly n times | [0-9]{4} | Matches 4-digit years like "2026" |
{n,m} | Between n and m times | [a-z]{3,8} | Matches words from 3 to 8 lowercase letters |
POSIX Predefined Character Classes
POSIX standards define standard bracketed character classes that are locale-aware:
| POSIX Class | Standard Equivalent | Description | Usage Example |
|---|---|---|---|
[[:alnum:]] | [a-zA-Z0-9] | Alphanumeric characters | ^[[:alnum:]]+$ |
[[:alpha:]] | [a-zA-Z] | Alphabetic letters only | ^[[:alpha:]]+$ |
[[:digit:]] | [0-9] | Numeric decimal digits | ^[[:digit:]]+$ |
[[:lower:]] | [a-z] | Lowercase letters | [[:lower:]] |
[[:upper:]] | [A-Z] | Uppercase letters | [[:upper:]] |
[[:space:]] | [ \t\r\n\v\f] | Whitespace characters | [[:space:]]+ |
[[:punct:]] | Punctuation symbols | Punctuation marks (e.g. ! " # $ % & ' ( )) | [[:punct:]] |
Code Examples: POSIX ereg vs Modern PCRE preg_match
<?php
// ============================================================================
// 1. VALIDATING A USERNAME (Letters, numbers, 3 to 16 chars)
// ============================================================================
$username = "shubh_2026";
// POSIX ereg (Legacy syntax - no /.../ delimiters):
// if (ereg("^[a-zA-Z0-9_]{3,16}$", $username)) { ... }
// Modern PCRE (PHP 7 & 8+ with /.../ delimiters):
if (preg_match("/^[a-zA-Z0-9_]{3,16}$/", $username)) {
echo "Valid Username: $username\n";
}
// ============================================================================
// 2. CASE-INSENSITIVE MATCHING (eregi vs preg_match with 'i' modifier)
// ============================================================================
$email = "SHUBH@XLAB.XYZ";
// POSIX eregi:
// if (eregi("\.xyz$", $email)) { ... }
// Modern PCRE (with /.../i modifier):
if (preg_match("/\.xyz$/i", $email)) {
echo "Valid .xyz Domain Email: $email\n";
}
// ============================================================================
// 3. GROUPING & CAPTURING SUBPATTERNS ()
// ============================================================================
$date = "2026-08-21";
// Captures (Year)-(Month)-(Day)
if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $regs)) {
echo "Full Date : " . $regs[0] . "\n";
echo "Year : " . $regs[1] . "\n";
echo "Month : " . $regs[2] . "\n";
echo "Day : " . $regs[3] . "\n";
}
// ============================================================================
// 4. LOGICAL OR ALTERNATION (|)
// ============================================================================
$file = "photo.png";
if (preg_match("/\.(jpg|jpeg|png|webp|gif)$/i", $file)) {
echo "Valid Image File: $file\n";
}
?>
Important PHP Output & Print Functions
PHP offers several distinct mechanisms to output and format data. Each function serves a dedicated role ranging from fast browser rendering to formatted strings and complex debugging:
Definition: echo is a language construct used to output one or more strings. It has no return value (void) and is slightly faster than print. It can accept multiple comma-separated arguments.
echo(string ...$expressions): void<?php
$name = "Shubh";
$age = 22;
// 1. Basic echo
echo "Hello, ", $name, "!
";
// 2. Multiple arguments (echo only)
echo "Name: ", $name, " | Age: ", $age, "\n";
// 3. Short Echo Tag (HTML Views)
// <?= $name ?> is equivalent to <?php echo $name; ?>
?>
Definition: print is also a language construct, but unlike echo, it always returns 1. Because it returns a value, it can be used inside expressions and ternary operators. Takes only a single argument.
print(string $expression): int (always returns 1)<?php
$isLoggedIn = true;
// 1. Basic print
print "Welcome to PHP Tutorials!\n";
// 2. Used inside an expression (returns 1)
$ret = print("Testing print return value\n");
echo "Return Value: " . $ret . "\n"; // Outputs: 1
// 3. Used in ternary operations
$isLoggedIn ? print("Status: Online\n") : print("Status: Offline\n");
?>
Definition: printf() outputs a formatted string according to format specifiers (such as %s, %d, %.2f) directly to the output buffer. Returns the length of the outputted string.
printf(string $format, mixed ...$values): int<?php
$product = "MacBook Pro";
$price = 1999.9;
$quantity = 3;
// Format string with string (%s), decimal (%d), and float with 2 decimals (%.2f)
printf("Product: %s | Qty: %02d | Price: $%.2f\n", $product, $quantity, $price);
// Number format in hexadecimal (%X) and binary (%b)
$number = 255;
printf("Decimal: %d | Hex: 0x%X | Binary: %b\n", $number, $number, $number);
?>
Definition: sprintf() is identical to printf(), with one critical difference: it does NOT print directly. Instead, it returns the formatted string so you can store it in a variable, database, or return from a function.
sprintf(string $format, mixed ...$values): string<?php
$userId = 42;
$score = 95.678;
// Store the formatted string in variable $formattedMsg
$formattedMsg = sprintf("User ID: %05d has scored %.1f%%", $userId, $score);
// Now you can log it, save to DB, or echo it later
echo $formattedMsg;
?>
Definition: var_dump() is the ultimate debugging tool in PHP. It outputs detailed structured information about variables, including their data type, length/count, and exact value. Highly useful for booleans (bool(false)), NULL, arrays, and objects.
var_dump(mixed $value, mixed ...$values): void<?php
$name = "Shubh";
$age = 22;
$isGraduated = true;
$skills = ["PHP", "MySQL", 2026];
var_dump($name);
var_dump($age);
var_dump($isGraduated);
var_dump($skills);
?>
Definition: print_r() prints human-readable information about a variable. Unlike var_dump(), it omits data types and lengths, making array/object trees much easier for humans to read. Setting $return = true returns the output as a string.
print_r(mixed $value, bool $return = false): mixed<?php
$user = [
"id" => 101,
"name" => "Shubh",
"roles" => ["Admin", "Author"],
"active" => true
];
// 1. Direct print
print_r($user);
// 2. Capture output as a string using $return = true
$outputString = print_r($user, true);
// file_put_contents('log.txt', $outputString);
?>
Complete Output & Print Functions Comparison Matrix
| Function / Construct | Type | Return Value | Multiple Args? | Outputs Data Type? | Best Use Case |
|---|---|---|---|---|---|
echo |
Language Construct | void (None) |
Yes (comma) | No | Standard, high-performance HTML & text output |
print |
Language Construct | int(1) Always |
No (single arg) | No | Conditional expressions / Ternary operations |
printf() |
Function | int (Output length) |
Yes (format + vars) | No | Directly printing formatted numbers, currency, dates |
sprintf() |
Function | string (Formatted string) |
Yes (format + vars) | No | Building strings for variables, SQL queries, logging |
var_dump() |
Function | void (None) |
Yes | Yes (with length) | Deep debugging (booleans, types, nulls, object internals) |
print_r() |
Function | bool|string |
No ($val, $return) | No | Clean human-readable inspection of arrays & objects |
printf() & sprintf() Format Specifiers Cheat Sheet:
| Specifier | Type / Description | Example Input | Formatted Output |
|---|---|---|---|
%s | String | sprintf("Hi %s", "Shubh") | Hi Shubh |
%d | Signed decimal integer | sprintf("%d", 42.9) | 42 |
%05d | Zero-padded integer (5 digits) | sprintf("%05d", 42) | 00042 |
%.2f | Floating-point (2 decimal places) | sprintf("%.2f", 19.9) | 19.90 |
%b | Binary number representation | sprintf("%b", 10) | 1010 |
%x / %X | Hexadecimal (lower / UPPER) | sprintf("%X", 255) | FF |
%c | ASCII character representation | sprintf("%c", 65) | A |
%% | Literal percent sign | sprintf("%d%%", 99) | 99% |
Variables & Data Types in PHP
In PHP, Variables are named storage containers used to hold data in memory throughout script execution. PHP is a dynamically-typed (loosely typed) language, meaning you do not need to declare data types explicitly before assigning values.
1. What is a Variable & Strict Naming Rules
A variable in PHP is declared dynamically the instant you assign a value to it using the assignment operator (=). Every variable name is prefixed with a dollar sign ($).
Rules for Naming PHP Variables:
| Rule | Requirement | Valid Examples | Invalid Examples |
|---|---|---|---|
Dollar Prefix ($) |
Must always begin with $. |
$name, $age |
name, @age |
| First Character | Must start with a letter (a-z, A-Z) or an underscore (_). Cannot start with a number. |
$score, $_sessionKey |
$1score, $4you |
| Allowed Characters | Can only contain alphanumeric characters (a-z, A-Z, 0-9) and underscores (_). No hyphens or symbols. |
$user_1, $itemPrice2 |
$user-id, $item% |
| Case Sensitivity | Variable names are strictly case-sensitive. | $age, $Age, $AGE are 3 distinct variables! |
Assuming $color equals $COLOR |
| Dynamic Memory | Variables do not require type declarations; PHP reallocates type automatically. | $x = 10; $x = "Text"; |
N/A |
Syntax & Example
<?php
// 1. Valid variable declarations
$username = "Shubh";
$_sessionToken = "auth_token_98765";
$userAge = 22; // camelCase (Standard PSR-12)
$user_email = "shubh@xlab.xyz"; // snake_case
// 2. Case-sensitivity demonstration
$city = "San Francisco";
$City = "Tokyo";
$CITY = "Berlin";
echo "city: $city | City: $City | CITY: $CITY\n";
// 3. Dynamic typing (Type changes upon re-assignment)
$data = 42; // Initially integer
var_dump($data);
$data = "Now a String"; // Changed to string
var_dump($data);
?>
2. Variable Scope & Lifecycle (Local, Global, Static)
The scope of a variable defines the boundary context where it is accessible and exists in memory. PHP has 3 primary variable scopes:
global keyword or $GLOBALS.
static, it retains its value even after the function finishes executing, across repeated function calls.
Comprehensive Scope Code Example
<?php
// ============================================================================
// 1. GLOBAL SCOPE & ACCESSING VIA global / $GLOBALS
// ============================================================================
$appName = "PHP Masterclass";
$version = "8.3";
function showAppDetails() {
// METHOD A: Using the 'global' keyword
global $appName;
// METHOD B: Using the superglobal $GLOBALS array
$ver = $GLOBALS['version'];
echo "App: $appName (v$ver)\n";
}
showAppDetails();
// ============================================================================
// 2. LOCAL SCOPE ISOLATION
// ============================================================================
function testLocal() {
$localVar = "I live only inside testLocal()";
}
testLocal();
// echo $localVar; // Warning: Undefined variable $localVar!
// ============================================================================
// 3. STATIC VARIABLE PERSISTENCE ACROSS CALLS
// ============================================================================
function countHits() {
static $hits = 0; // Initialized once only
$hits++;
echo "Visit Count: $hits\n";
}
countHits(); // Output: Visit Count: 1
countHits(); // Output: Visit Count: 2
countHits(); // Output: Visit Count: 3
?>
3. Variable Variables (Dynamic Variable Names: $$var)
In PHP, a Variable Variable takes the string value of a variable and treats that value as the name of another variable. It is written using double dollar signs ($$).
$varName = "role";
$$varName = "Administrator"; // Creates a variable named $role and assigns "Administrator"
echo $role; // Outputs: Administrator
Practical Example & Dynamic Form Population:
<?php
// 1. Basic Variable Variable
$key = "author";
$$key = "Shubh"; // Creates $author = "Shubh"
echo "Value of \$key : " . $key . "\n";
echo "Value of \$\$key : " . $$key . "\n";
echo "Value of \$author : " . $author . "\n\n";
// 2. Real-World Use Case: Dynamic Request Parameter Binding
$requestData = [
'title' => 'PHP 8 Master Guide',
'rating' => 4.9,
'tags' => 'backend, web, development'
];
foreach ($requestData as $field => $value) {
$$field = $value; // Dynamically creates $title, $rating, and $tags!
}
echo "Extracted Title : $title\n";
echo "Extracted Rating : $rating ⭐\n";
echo "Extracted Tags : $tags\n";
?>
4. Constants & Magic Constants in PHP
A Constant is an identifier (name) for a simple value that cannot be changed or undefined once defined. Constants do not start with a dollar sign ($) and are automatically global across the entire script.
Defining Constants: define() vs const
| Feature | define('NAME', value) |
const NAME = value; |
|---|---|---|
| Execution Stage | Runtime function (evaluated when executed) | Compile-time language construct (evaluated at compile time) |
| Conditional Use (if/loops) | Supported (Can be placed inside if blocks) |
Not allowed at root conditional blocks |
| Class Scope (OOP) | Cannot be used to define class constants | Standard for class constants (Class::CONST) |
| Performance | Standard function call | Faster execution (resolved at compile time) |
PHP Magic Constants Reference
Magic constants change dynamically depending on where they are called in code:
| Magic Constant | Description | Example Return Value |
|---|---|---|
__DIR__ | The directory of the current file | /public_html/phpwithshubh |
__FILE__ | The full filesystem path and filename of the current file | /var/www/index.php |
__LINE__ | The current line number of the file | 42 |
__FUNCTION__ | The function name where it is declared | calculateTotal |
__CLASS__ | The class name (including namespace) | App\Models\User |
__METHOD__ | The class method name | App\Models\User::save |
__NAMESPACE__ | The current namespace name | App\Controllers |
Constants Code Example
<?php
// 1. Defining constants
define("SITE_NAME", "PHP Masterclass with Shubh");
define("DB_PORT", 3306);
const MAX_UPLOAD_LIMIT_MB = 100;
echo "Site: " . SITE_NAME . " | Max Upload: " . MAX_UPLOAD_LIMIT_MB . "MB\n\n";
// 2. Using Magic Constants
echo "Current File Line : " . __LINE__ . "\n";
echo "Current Directory : " . __DIR__ . "\n";
echo "Current File Path : " . __FILE__ . "\n";
function trackExecution() {
echo "Running inside function: " . __FUNCTION__ . "() on line " . __LINE__ . "\n";
}
trackExecution();
?>
5. The 10 PHP 8 Data Types (Master Taxonomy)
PHP 8 supports 10 primitive and structured data types divided into 3 fundamental groups: Scalar Types, Compound Types, and Special Types.
| Category | Data Type | Sample Value / Syntax | Description |
|---|---|---|---|
| Scalar Types (Single Value) |
bool |
true, false |
Logical state value (Boolean). Evaluated in conditional branches. |
int |
42, -17, 0x1F, 0b1010 |
Signed whole integer numbers (Decimal, Hexadecimal, Binary, Octal). | |
float (double) |
19.99, -0.5, 1.5e3 |
Floating-point fractional numbers and scientific notation numbers. | |
string |
"PHP 8", 'Shubh' |
Binary-safe character byte sequences (Single, Double, Heredoc, Nowdoc). | |
| Compound Types (Complex Structures) |
array |
['PHP', 'MySQL'], ['id' => 1] |
Ordered map holding zero or more values with integer or string keys. |
object |
new User(), (object)['a' => 1] |
Instance of a user-defined class containing properties and methods. | |
callable |
fn($x) => $x * 2, 'strlen' |
A reference to a callable function, closure, or class method. | |
iterable |
array or Traversable |
Pseudo-type matching anything that can be looped using foreach. |
|
| Special Types (Special Handlers) |
null |
null, NULL |
Represents a variable with no assigned value or explicitly unset. |
resource |
fopen('file.txt', 'r') |
Holds a reference to an external resource (open file streams, sockets, DB). |
Scalar Types In-Depth:
- Boolean
false - Integer
0and Float0.0/-0.0 - Empty string
""and string zero"0" - Empty array
[] - Special type
null
-1, non-empty strings) are truthy!
$dec = 1234; // Decimal
$hex = 0x1A; // Hexadecimal (26)
$bin = 0b1101; // Binary (13)
$oct = 0o14; // Octal (12)
$large = 1_000_000; // Numeric separator (1 million)
6. Type Checking, Type Juggling & Explicit Casting
Because PHP is dynamically typed, it performs Type Juggling (Coercion) automatically when evaluating expressions. You can also enforce Explicit Type Casting or activate Strict Types.
Type Inspection Functions in PHP:
| Function | Checks For | Example | Result |
|---|---|---|---|
gettype($var) | Returns string name of data type | gettype(42) | "integer" |
is_int($var) | Checks if variable is integer | is_int(100) | true |
is_string($var) | Checks if variable is string | is_string("PHP") | true |
is_bool($var) | Checks if variable is boolean | is_bool(false) | true |
is_float($var) | Checks if variable is float | is_float(3.14) | true |
is_array($var) | Checks if variable is array | is_array([1, 2]) | true |
is_null($var) | Checks if variable is null | is_null($x) | true |
is_numeric($var) | Checks if variable is number or numeric string | is_numeric("123.45") | true |
Explicit Type Casting Syntax:
| Cast Operator | Target Data Type | Example Input | Casted Result |
|---|---|---|---|
(int) or (integer) | Integer | (int)"42px" | int(42) |
(float) or (double) | Float | (float)"19.99" | float(19.99) |
(string) | String | (string)100 | string(3) "100" |
(bool) or (boolean) | Boolean | (bool)0 | bool(false) |
(array) | Array | (array)"text" | array(1) { [0] => "text" } |
(object) | Object (stdClass) | (object)['a' => 1] | stdClass Object ( [a] => 1 ) |
Complete Type Casting & Strict Types Example
<?php
// 1. Explicit Type Casting
$rawPrice = "99.50 USD";
$priceFloat = (float)$rawPrice;
$priceInt = (int)$rawPrice;
var_dump($priceFloat); // float(99.5)
var_dump($priceInt); // int(99)
// 2. Type Checking Functions
$score = "100";
if (is_numeric($score)) {
echo "\$score is valid numeric data!\n";
}
// 3. Array to Object Casting
$userArray = ["id" => 42, "name" => "Shubh"];
$userObj = (object)$userArray;
echo "User Object Property: " . $userObj->name . "\n";
// 4. Strict Typing Example
// declare(strict_types=1); enforces exact parameter and return types:
function calculateTotal(int $quantity, float $price): float {
return $quantity * $price;
}
echo "Total: $" . calculateTotal(3, 19.99) . "\n";
?>
Arrays & Array Functions in PHP
An Array in PHP is an ordered map that associates values to keys. Unlike arrays in C or Java, PHP arrays are dynamic, grow automatically in size, and can hold mixed data types (integers, strings, floats, booleans, objects, and other arrays) simultaneously.
1. The 3 Types of PHP Arrays
0.
$frameworks = ["Laravel", "Symfony", "CodeIgniter"];
echo $frameworks[0]; // "Laravel"
$frameworks[] = "Yii"; // Appends at next auto-index (3)
=> arrow operator.
$user = [
"username" => "shubh_dev",
"role" => "Admin",
"xp" => 9500
];
echo $user["role"]; // "Admin"
$products = [
["id" => 101, "title" => "MacBook Pro", "price" => 1999.00],
["id" => 102, "title" => "4K Monitor", "price" => 499.00]
];
echo $products[0]["title"] . ": $" . $products[0]["price"]; // MacBook Pro: $1999.00
2. Array Iteration, Reference Modification & Unpacking
| Syntax / Technique | Mechanism | Code Example |
|---|---|---|
foreach ($arr as $val) |
Iterates over values without keys | foreach ($fruits as $fruit) { ... } |
foreach ($arr as $key => $val) |
Iterates with both key and value | foreach ($user as $k => $v) { echo "$k: $v"; } |
By-Reference Modification (&$val) |
Directly modifies original array elements in place | foreach ($prices as &$p) { $p *= 1.18; } unset($p); |
Array Destructuring ([$a, $b]) |
Extracts values into discrete variables | [$id, $name] = [101, "Shubh"]; |
Spread Operator (...$arr) |
Unpacks elements into another array or function call | $merged = [...$arr1, ...$arr2]; |
<?php
// 1. Modifying by reference in foreach
$scores = [80, 90, 100];
foreach ($scores as &$score) {
$score += 5; // Adds bonus 5 points to each
}
unset($score); // Break reference to prevent bugs!
print_r($scores); // [85, 95, 105]
// 2. Modern Array Destructuring with keys
$book = ['title' => 'Clean Code', 'author' => 'Robert Martin', 'year' => 2008];
['title' => $title, 'author' => $author] = $book;
echo "Book: $title by $author
";
// 3. Array Spread Unpacking
$frontend = ['HTML', 'CSS', 'JS'];
$backend = ['PHP', 'MySQL'];
$fullstack = [...$frontend, ...$backend, 'Docker'];
print_r($fullstack);
?>
3. Essential 30+ PHP Array Functions Matrix
| Category | Function | Syntax | Description |
|---|---|---|---|
| Search & Verification | in_array() |
in_array($needle, $haystack, $strict = false): bool |
Checks if a value exists in an array. |
array_key_exists() |
array_key_exists($key, $array): bool |
Checks if a specific key exists (even if value is null). | |
array_search() |
array_search($needle, $haystack): int|string|false |
Searches for value and returns corresponding key. | |
isset($arr[$k]) |
isset($array[$key]): bool |
Language construct; checks if key exists & is not null (fastest). | |
| Stack & Queue Ops | array_push() |
array_push(&$arr, ...$vals): int |
Pushes one or more elements onto the end of array. |
array_pop() |
array_pop(&$arr): mixed |
Pops and returns the last element off array. | |
array_unshift() |
array_unshift(&$arr, ...$vals): int |
Prepends one or more elements to the beginning. | |
array_shift() |
array_shift(&$arr): mixed |
Shifts and returns the first element off array. | |
| Transformation & Keys | array_keys() |
array_keys($arr): array |
Returns all the keys of an array. |
array_values() |
array_values($arr): array |
Returns all the values and re-indexes sequentially. | |
array_column() |
array_column($arr, $column_key): array |
Extracts a single column from multidimensional array. | |
array_unique() |
array_unique($arr): array |
Removes duplicate values from an array. |
4. Complete PHP Array Sorting Functions Reference
| Sorting Function | Sorts By | Order | Key Preservation |
|---|---|---|---|
sort($arr) | Value | Ascending (A-Z, 0-9) | Re-indexes (0, 1, 2) |
rsort($arr) | Value | Descending (Z-A, 9-0) | Re-indexes |
asort($arr) | Value | Ascending | Preserves Keys |
arsort($arr) | Value | Descending | Preserves Keys |
ksort($arr) | Key | Ascending | Preserves Keys |
krsort($arr) | Key | Descending | Preserves Keys |
usort($arr, $fn) | Custom Callback | User Defined | Re-indexes |
uasort($arr, $fn) | Custom Callback | User Defined | Preserves Keys |
<?php
// 1. Associative sorting preserving keys
$salaries = ["Carol" => 75000, "Alice" => 95000, "Bob" => 60000];
asort($salaries); // Sort by salary ascending while keeping names
print_r($salaries);
// 2. Custom multidimensional sort using the spaceship operator (<=>)
$users = [
["name" => "Shubh", "age" => 22],
["name" => "Alex", "age" => 30],
["name" => "John", "age" => 25]
];
usort($users, fn($a, $b) => $a['age'] <=> $b['age']); // Sort by age ascending
print_r($users);
?>
5. Functional Transformations: array_map, array_filter & array_reduce
<?php
$products = [
["name" => "Laptop", "price" => 1200, "in_stock" => true],
["name" => "Mouse", "price" => 25, "in_stock" => false],
["name" => "Desk", "price" => 350, "in_stock" => true]
];
// 1. array_filter: Keep only items in stock
$inStock = array_filter($products, fn($p) => $p['in_stock']);
// 2. array_map: Extract uppercase product names with 10% tax
$formatted = array_map(fn($p) => [
'item' => strtoupper($p['name']),
'total_with_tax' => $p['price'] * 1.10
], $inStock);
// 3. array_reduce: Calculate grand total inventory value
$grandTotal = array_reduce($inStock, fn($sum, $p) => $sum + $p['price'], 0);
print_r($formatted);
echo "Grand Total Inventory: $" . number_format($grandTotal, 2) . "
";
?>
Functions & Scopes in PHP
Functions in PHP are reusable blocks of code that perform a specific task, take inputs (parameters), and return computed outputs. Modern PHP 8+ supports robust type declarations, named arguments, closures, and arrow functions.
1. Function Declaration, Named Arguments & Variadics
function setCookieConfig(string $name, int $expire = 3600, bool $secure = true) {}
// Call by name:
setCookieConfig(name: 'session', secure: false);
...)function sum(int ...$numbers): int {
return array_sum($numbers);
}
echo sum(10, 20, 30, 40); // 100
<?php
// 1. Default Parameters & Pass by Reference (&$value)
function applyDiscount(float &$price, float $percentage = 10.0): void {
$price -= ($price * ($percentage / 100));
}
$itemPrice = 100.00;
applyDiscount($itemPrice, 20.0); // Directly alters $itemPrice
echo "Discounted Price: $itemPrice
";
// 2. Named Arguments (PHP 8)
function createUser(string $name, string $role = "Subscriber", bool $isActive = true): string {
return "User: $name | Role: $role | Active: " . ($isActive ? 'Yes' : 'No');
}
// Skips $role and specifies $isActive directly:
echo createUser(name: "Shubh", isActive: true) . "
";
?>
2. Return Types & Union Types in PHP 8
| Return Type | Meaning | Example Signature |
|---|---|---|
int, string, bool, array | Strict single primitive return | function getAge(): int |
void | Returns nothing (no value) | function logEvent(): void |
never (PHP 8.1+) | Never returns (always throws or exits) | function redirect(): never |
int|float (Union) | Can return either an int or float | function calculate(): int|float |
?string (Nullable) | Can return string or null | function findEmail(): ?string |
mixed | Explicitly allows any return type | function inspect(): mixed |
3. Anonymous Functions (Closures) & Arrow Functions (fn())
<?php
// 1. Anonymous Closure with 'use' to capture parent scope
$taxRate = 0.18;
$calculateTotal = function(float $subtotal) use ($taxRate): float {
return $subtotal + ($subtotal * $taxRate);
};
echo "Closure Total: $" . $calculateTotal(100.00) . "
";
// 2. Concise Arrow Function (auto-captures $taxRate by value)
$calcArrow = fn(float $subtotal): float => $subtotal * (1 + $taxRate);
echo "Arrow Function Total: $" . $calcArrow(200.00) . "
";
// 3. First-Class Callable Syntax (PHP 8.1+)
$funcRef = strtoupper(...);
echo $funcRef("learn php with shubh") . "
";
?>
Object-Oriented PHP (OOP Mastery)
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which contain data in the form of properties and code in the form of methods. Modern PHP supports classes, inheritance, interfaces, traits, and constructor property promotion.
1. Classes, Objects & Constructor Property Promotion (PHP 8+)
<?php
class User {
// PHP 8 Constructor Property Promotion:
// Declares visibility + data type directly in constructor arguments!
public function __construct(
public readonly int $id,
public string $name,
private string $email,
protected string $role = "Developer"
) {}
public function getDetails(): string {
return "User #{$this->id}: {$this->name} ({$this->role}) - Email: {$this->email}";
}
public function setEmail(string $newEmail): void {
if (filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
$this->email = $newEmail;
}
}
}
$user = new User(101, "Shubh", "shubh@xlab.xyz", "Lead Architect");
echo $user->getDetails() . "
";
echo "Accessing Public Property: " . $user->name . "
";
?>
2. Inheritance, Polymorphism & Access Modifiers
| Access Modifier | Same Class | Child Class (Inherited) | Outside Class (Global) |
|---|---|---|---|
public | Accessible | Accessible | Accessible |
protected | Accessible | Accessible | No Access |
private | Accessible | No Access | No Access |
3. Abstract Classes vs Interfaces
<?php
// Contract Interface
interface PaymentGatewayInterface {
public function charge(float $amount): bool;
}
// Concrete Implementation 1
class StripeGateway implements PaymentGatewayInterface {
public function charge(float $amount): bool {
echo "Processing $amount via Stripe API...
";
return true;
}
}
// Concrete Implementation 2
class PayPalGateway implements PaymentGatewayInterface {
public function charge(float $amount): bool {
echo "Processing $amount via PayPal Gateway...
";
return true;
}
}
// Polymorphic Processor
function checkout(PaymentGatewayInterface $gateway, float $total) {
$gateway->charge($total);
}
checkout(new StripeGateway(), 199.99);
checkout(new PayPalGateway(), 49.50);
?>
4. Traits (Horizontal Code Reuse) & PSR-4 Namespaces
<?php
trait LoggableTrait {
public function log(string $message): void {
echo "[" . date('Y-m-d H:i:s') . "] LOG: $message
";
}
}
class OrderService {
use LoggableTrait; // Injects log() method horizontally
public function createOrder(int $orderId) {
$this->log("Order #$orderId successfully placed.");
}
}
$service = new OrderService();
$service->createOrder(98765);
?>
MySQL & PDO (PHP Data Objects)
PDO (PHP Data Objects) is the official database abstraction layer in PHP. It provides a uniform interface to connect to databases (MySQL, PostgreSQL, SQLite), supports Prepared Statements to guarantee immunity against SQL Injection attacks, and handles transactions.
1. Secure PDO Connection Setup & Error Handling
<?php
$host = 'localhost';
$db = 'php_masterclass';
$user = 'root';
$pass = 'secure_password';
$charset = 'utf8mb4';
// 1. Data Source Name (DSN)
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
// 2. Recommended PDO Configuration Options
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Throw exceptions on errors
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Return associative arrays
PDO::ATTR_EMULATE_PREPARES => false, // Native prepared statements
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
echo "Connected to MySQL successfully via PDO!
";
} catch (PDOException $e) {
die("Database Connection Error: " . $e->getMessage());
}
?>
2. Complete CRUD with Prepared Statements (SQL Injection Immunity)
Prepared statements separate the SQL query logic from user-supplied data, ensuring untrusted user inputs cannot modify query execution.
<?php
// ============================================================================
// 1. CREATE (INSERT) WITH NAMED PLACEHOLDERS (:name, :email)
// ============================================================================
$stmt = $pdo->prepare("INSERT INTO users (name, email, role) VALUES (:name, :email, :role)");
$stmt->execute([
':name' => 'Shubh',
':email' => 'shubh@xlab.xyz',
':role' => 'Admin'
]);
$userId = $pdo->lastInsertId();
echo "Inserted User ID: $userId
";
// ============================================================================
// 2. READ (SELECT) WITH PARAMETER BINDING
// ============================================================================
$stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE role = :role LIMIT :limit");
$stmt->bindValue(':role', 'Admin', PDO::PARAM_STR);
$stmt->bindValue(':limit', 10, PDO::PARAM_INT);
$stmt->execute();
$admins = $stmt->fetchAll(); // Returns all rows as assoc array
print_r($admins);
// ============================================================================
// 3. UPDATE RECORD & CHECK ROW COUNT
// ============================================================================
$updateStmt = $pdo->prepare("UPDATE users SET name = :name WHERE id = :id");
$updateStmt->execute([':name' => 'Shubh (Verified)', ':id' => $userId]);
echo "Rows Updated: " . $updateStmt->rowCount() . "
";
// ============================================================================
// 4. DELETE RECORD SAFELY
// ============================================================================
$delStmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
$delStmt->execute([':id' => $userId]);
echo "Deleted User #$userId successfully.
";
?>
3. Database Transactions & ACID Compliance
Transactions allow running multiple SQL queries as a single atomic operation. If any query fails, all changes are rolled back automatically.
<?php
try {
// 1. Begin atomic transaction
$pdo->beginTransaction();
$fromAccountId = 1;
$toAccountId = 2;
$transferAmount = 250.00;
// Step A: Deduct from Sender
$stmt1 = $pdo->prepare("UPDATE accounts SET balance = balance - :amt WHERE id = :id");
$stmt1->execute([':amt' => $transferAmount, ':id' => $fromAccountId]);
// Step B: Credit to Receiver
$stmt2 = $pdo->prepare("UPDATE accounts SET balance = balance + :amt WHERE id = :id");
$stmt2->execute([':amt' => $transferAmount, ':id' => $toAccountId]);
// 2. Commit transaction if both succeeded
$pdo->commit();
echo "Funds transferred successfully!
";
} catch (Exception $e) {
// 3. Rollback changes if anything failed
$pdo->rollBack();
echo "Transaction failed and rolled back: " . $e->getMessage() . "
";
}
?>
Essential PHP String Functions Library
PHP provides over 100 built-in string functions. Below are the most important, widely-used functions categorized with their definition, syntax, and live examples.
Returns the length (number of bytes/characters) of a given string.
strlen(string $string): int$str = "Shubh";
echo strlen($str); // Outputs: 5
Counts the number of words inside a string or returns an array of words.
str_word_count(string $string, int $format = 0): mixed$text = "Master PHP with Shubh";
echo str_word_count($text); // Outputs: 4
Finds the position (0-indexed) of the first occurrence of a substring. Case-sensitive.
strpos(string $haystack, string $needle, int $offset = 0): int|false$msg = "Hello World!";
echo strpos($msg, "World"); // Outputs: 6
Finds position of first occurrence of a substring (Case-Insensitive).
stripos(string $haystack, string $needle): int|false$email = "user@GMAIL.COM";
echo stripos($email, "gmail"); // Outputs: 5
Checks if a string contains a specific substring. Returns true or false.
str_contains(string $haystack, string $needle): bool$url = "https://example.com/api/v1";
var_dump(str_contains($url, "api")); // bool(true)
Determines whether a string begins or ends with a specific prefix or suffix.
str_starts_with($str, $prefix) / str_ends_with($str, $suffix)$file = "invoice_2026.pdf";
echo str_ends_with($file, ".pdf"); // Outputs: 1 (true)
Converts all characters of a string to lowercase.
strtolower(string $string): string$name = "SHUBH PATEL";
echo strtolower($name); // Outputs: shubh patel
Converts all characters of a string to uppercase.
strtoupper(string $string): string$title = "php developer";
echo strtoupper($title); // Outputs: PHP DEVELOPER
Converts the first character of a string to uppercase or lowercase.
ucfirst(string $str) | lcfirst(string $str)echo ucfirst("shubh"); // Outputs: Shubh
echo lcfirst("HELLO"); // Outputs: hELLO
Capitalizes the first character of each word in a string.
ucwords(string $string, string $separators = " \t\r\n\f\v"): string$heading = "learn php backend development";
echo ucwords($heading); // Outputs: Learn Php Backend Development
Replaces all occurrences of a search string with a replacement string.
str_replace($search, $replace, $subject, &$count = null)$phrase = "I love Python";
echo str_replace("Python", "PHP", $phrase); // Outputs: I love PHP
Extracts and returns a portion of a string specified by start offset and length.
substr(string $string, int $offset, ?int $length = null): string$str = "Antigravity";
echo substr($str, 0, 4); // Outputs: Anti
echo substr($str, 4); // Outputs: gravity
Reverses a string, or repeats a string N number of times.
strrev($str) | str_repeat($str, $times)echo strrev("PHP"); // Outputs: PHP (Palindrome!)
echo str_repeat("=-", 5); // Outputs: =-=-=-=-=-
Splits a string by a delimiter and returns an array of substrings.
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array$skills = "PHP,MySQL,HTML,CSS";
$array = explode(",", $skills);
print_r($array);
// Array ( [0] => PHP [1] => MySQL [2] => HTML [3] => CSS )
Joins array elements with a glue string into a single string.
implode(string $separator, array $array): string$tags = ['coding', 'webdev', 'php'];
echo implode(" #", $tags); // Outputs: coding #webdev #php
Strips whitespace (or custom characters) from beginning and/or end of string.
trim(string $string, string $characters = " \n\r\t\v\0")$input = " Hello World! ";
echo "'" . trim($input) . "'"; // Outputs: 'Hello World!'
Converts special characters (like <, >, &, ") to HTML entities (Crucial for XSS Security!).
htmlspecialchars($string, $flags = ENT_QUOTES | ENT_SUBSTITUTE)$unsafe = "<script>alert('Hacked!');</script>";
echo htmlspecialchars($unsafe);
// Outputs: <script>alert('Hacked!');</script>
Pads a string to a new specified length with another string (useful for invoice IDs, numbers).
str_pad($str, $length, $pad_string = " ", $pad_type = STR_PAD_RIGHT)$invoiceId = "42";
echo str_pad($invoiceId, 6, "0", STR_PAD_LEFT);
// Outputs: 000042
Interactive PHP String & Output IDE
Test string functions, pattern operations, and print formats directly in your browser. Live evaluation runs in real-time as you type: