PHP 8.3 Core Fundamentals

Master PHP.
Variables, Types, Strings & Output.

A meticulous, production-grade reference and interactive playground for PHP developers. Designed with precision, clarity, and zero fluff.

10 Data Types
4 String Literals
6 Output Engines
POSIX & PCRE RegEx
30+ Core Functions

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).

No Specific String Size Limit:

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).

4 Ways to Specify a String Literal:

PHP gives you 4 distinct syntaxes: Single Quoted, Double Quoted, Heredoc, and Nowdoc.

basic_strings.php
<?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 $name are 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

single_quoted.php
<?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;
?>
Execution Output:
Author is $author It's a wonderful day! C:\xampp\htdocs Line 1\nLine 2

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
\nLinefeed / Newline"Hello\nWorld"2 lines
\rCarriage Return"Hello\rWorld"CR control char
\tHorizontal 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

double_quoted.php
<?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!";
?>
Execution Output:
Hello, Shubh! Welcome to PHP Mastery. Role: Admin (XP: 500) He drank 3 glasses. Special Offer: "Buy 1 Get 1 Free" for only $19.99! Tabbed Columns Data Unicode support: 🚀 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

heredoc_example.php
<?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;
?>
Execution Output:
<div class="card"> <h2>Certificate of Completion</h2> <p>Congratulations, <strong>Shubh</strong>!</p> <p>You scored <span class="badge">98%</span> in <em>Backend Web Development</em>.</p> <button onclick="alert('Welcome to PHP!')">Download Certificate</button> </div>

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

nowdoc_example.php
<?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;
?>
Execution Output:
<?php // In Nowdoc, $name and $count are NOT evaluated! $name = "Guest"; $count = 10; for ($i = 0; $i < $count; $i++) { echo "Iteration $i: $name\n"; } ?>

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
Single Quotes Code
<?php
$fruit = "Apple";
echo 'I love $fruit\n';
// Output: I love $fruit\n
?>
Double Quotes Code
<?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
Heredoc Example
<?php
$table = "users";
$role = "admin";
$sql = <<<SQL
SELECT id, email 
FROM {$table} 
WHERE role = '$role';
SQL;
// Variables $table & $role are populated!
?>
Nowdoc Example
<?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.

explode() Decomposition

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
$separator (string)
The boundary delimiter to split by (e.g. ",", "/", " "). Cannot be empty "".
$string (string)
The input target string to be decomposed into substrings.
$limit (int, optional)
Controls the maximum number of elements returned:
  • Positive ($limit > 0): Returns up to $limit elements. The final element contains the remainder of the string.
  • Negative ($limit < 0): Returns all elements except the last -$limit elements.
explode_examples.php
<?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']
?>
explode() Output:
Array ( [0] => PHP [1] => MySQL [2] => HTML [3] => CSS [4] => JavaScript ) --- Positive Limit (3 parts) --- Array ( [0] => user [1] => profile [2] => settings/security )
implode() (alias: join) Composition

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
$separator (string, optional)
The glue string placed between each array element (e.g. ", ", " -> ", "-"). Defaults to empty string "".
$array (array)
The array of strings or numeric values to concatenate into a single continuous string.
join() Alias
join() is an exact built-in alias of implode() with identical behavior and zero performance overhead.
implode_examples.php
<?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;
?>
implode() Output:
PHP 8 -> Laravel -> MySQL -> Tailwind SELECT * FROM users WHERE role IN ('admin', 'editor', 'moderator'); <span class="badge">Web</span> <span class="badge">Backend</span> <span class="badge">Security</span>

Additional String Decomposing Functions in PHP

str_split() — Fixed Length Chunking
Splits a string into equal-length character chunks without needing a delimiter.
$str = "SHUBH";
$chars = str_split($str, 1); 
// ['S', 'H', 'U', 'B', 'H']

$chunks = str_split("12345678", 2);
// ['12', '34', '56', '78']
strtok() — Token By Token Parser
Tokenizes a string step-by-step using multiple possible delimiters (e.g. spaces, commas, slashes).
$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

1. POSIX Extended RegEx (Historical Standard)

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.

No Delimiters PHP 4 - 5.3
2. PCRE — Perl Compatible (Modern Standard)

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.

PHP 7 / 8+ Standard High Performance

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*cMatches "ac", "abc", "abbbbc"
+1 or more times (at least once)ab+cMatches "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 symbolsPunctuation marks (e.g. ! " # $ % & ' ( ))[[:punct:]]

Code Examples: POSIX ereg vs Modern PCRE preg_match

regex_posix_vs_pcre.php
<?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";
}
?>
Execution Output:
Valid Username: shubh_2026 Valid .xyz Domain Email: SHUBH@XLAB.XYZ Full Date : 2026-08-21 Year : 2026 Month : 08 Day : 21 Valid Image File: photo.png

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

variables_basics.php
<?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);
?>
Execution Output:
city: San Francisco | City: Tokyo | CITY: Berlin int(42) string(12) "Now a String"

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:

1. Local Scope
Variables declared inside a function have local scope. They exist only while the function is executing and are destroyed when the function terminates.
2. Global Scope
Variables declared outside all functions have global scope. They cannot be directly accessed inside a function unless using the global keyword or $GLOBALS.
3. Static Scope
When a local variable is declared with static, it retains its value even after the function finishes executing, across repeated function calls.
4. Function Parameter Scope
Function arguments behave as local variables initialized with the values passed by caller.

Comprehensive Scope Code Example

variable_scopes.php
<?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
?>
Execution Output:
App: PHP Masterclass (v8.3) Visit Count: 1 Visit Count: 2 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:

variable_variables.php
<?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";
?>
Execution Output:
Value of $key : author Value of $$key : Shubh Value of $author : Shubh Extracted Title : PHP 8 Master Guide Extracted Rating : 4.9 ⭐ Extracted Tags : backend, web, development

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 file42
__FUNCTION__The function name where it is declaredcalculateTotal
__CLASS__The class name (including namespace)App\Models\User
__METHOD__The class method nameApp\Models\User::save
__NAMESPACE__The current namespace nameApp\Controllers

Constants Code Example

constants_demo.php
<?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();
?>
Execution Output:
Site: PHP Masterclass with Shubh | Max Upload: 100MB Current File Line : 10 Current Directory : C:\xampp\htdocs\php Current File Path : C:\xampp\htdocs\php\constants_demo.php Running inside function: trackExecution() on line 15

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:

1. Booleans & Truthiness in PHP
In PHP, the following values are automatically considered falsy:
  • Boolean false
  • Integer 0 and Float 0.0 / -0.0
  • Empty string "" and string zero "0"
  • Empty array []
  • Special type null
All other values (including negative numbers like -1, non-empty strings) are truthy!
2. Integer Formats & Number Separators
PHP 8 supports multiple integer notation formats:
$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 typegettype(42)"integer"
is_int($var)Checks if variable is integeris_int(100)true
is_string($var)Checks if variable is stringis_string("PHP")true
is_bool($var)Checks if variable is booleanis_bool(false)true
is_float($var)Checks if variable is floatis_float(3.14)true
is_array($var)Checks if variable is arrayis_array([1, 2])true
is_null($var)Checks if variable is nullis_null($x)true
is_numeric($var)Checks if variable is number or numeric stringis_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)100string(3) "100"
(bool) or (boolean)Boolean(bool)0bool(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

type_casting_demo.php
<?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";
?>
Execution Output:
float(99.5) int(99) $score is valid numeric data! User Object Property: Shubh Total: $59.97

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

1. Indexed Arrays (Numeric Keys)
Elements are indexed automatically with sequential numbers starting at 0.
$frameworks = ["Laravel", "Symfony", "CodeIgniter"];
echo $frameworks[0]; // "Laravel"
$frameworks[] = "Yii"; // Appends at next auto-index (3)
2. Associative Arrays (Named Keys)
Elements use custom named string keys via the => arrow operator.
$user = [
    "username" => "shubh_dev",
    "role"     => "Admin",
    "xp"       => 9500
];
echo $user["role"]; // "Admin"
3. Multidimensional Arrays (Nested Trees)
Arrays that contain other arrays as elements, creating tables, matrices, and JSON-like tree hierarchies.
$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];
array_iteration_demo.php
<?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);
?>
Execution Output:
Array ( [0] => 85 [1] => 95 [2] => 105 ) Book: Clean Code by Robert Martin Array ( [0] => HTML [1] => CSS [2] => JS [3] => PHP [4] => MySQL [5] => Docker )

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)ValueAscending (A-Z, 0-9)Re-indexes (0, 1, 2)
rsort($arr)ValueDescending (Z-A, 9-0)Re-indexes
asort($arr)ValueAscendingPreserves Keys
arsort($arr)ValueDescendingPreserves Keys
ksort($arr)KeyAscendingPreserves Keys
krsort($arr)KeyDescendingPreserves Keys
usort($arr, $fn)Custom CallbackUser DefinedRe-indexes
uasort($arr, $fn)Custom CallbackUser DefinedPreserves Keys
array_sorting_demo.php
<?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);
?>
Execution Output:
Array ( [Bob] => 60000 [Carol] => 75000 [Alice] => 95000 ) Array ( [0] => Array ( [name] => Shubh, [age] => 22 ) [1] => Array ( [name] => John, [age] => 25 ) [2] => Array ( [name] => Alex, [age] => 30 ) )

5. Functional Transformations: array_map, array_filter & array_reduce

functional_arrays.php
<?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) . "
";
?>
Execution Output:
Array ( [0] => Array ( [item] => LAPTOP [total_with_tax] => 1320 ) [2] => Array ( [item] => DESK [total_with_tax] => 385 ) ) Grand Total Inventory: $1,550.00

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

Named Arguments (PHP 8.0+)
Allows passing arguments based on parameter name rather than position. Skip defaults cleanly!
function setCookieConfig(string $name, int $expire = 3600, bool $secure = true) {}
// Call by name:
setCookieConfig(name: 'session', secure: false);
Variadic Functions (Splat ...)
Accepts a variable number of arguments packed into an array.
function sum(int ...$numbers): int {
    return array_sum($numbers);
}
echo sum(10, 20, 30, 40); // 100
functions_mastery.php
<?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) . "
";
?>
Execution Output:
Discounted Price: $80 User: Shubh | Role: Subscriber | Active: Yes

2. Return Types & Union Types in PHP 8

Return Type Meaning Example Signature
int, string, bool, arrayStrict single primitive returnfunction getAge(): int
voidReturns 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 floatfunction calculate(): int|float
?string (Nullable)Can return string or nullfunction findEmail(): ?string
mixedExplicitly allows any return typefunction inspect(): mixed

3. Anonymous Functions (Closures) & Arrow Functions (fn())

closures_demo.php
<?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") . "
";
?>
Execution Output:
Closure Total: $118 Arrow Function Total: $236 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+)

user_class_demo.php
<?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 . "
";
?>
Execution Output:
User #101: Shubh (Lead Architect) - Email: shubh@xlab.xyz Accessing Public Property: Shubh

2. Inheritance, Polymorphism & Access Modifiers

Access Modifier Same Class Child Class (Inherited) Outside Class (Global)
publicAccessibleAccessibleAccessible
protectedAccessibleAccessibleNo Access
privateAccessibleNo AccessNo Access

3. Abstract Classes vs Interfaces

payment_interface.php
<?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);
?>
Execution Output:
Processing $199.99 via Stripe API... Processing $49.5 via PayPal Gateway...

4. Traits (Horizontal Code Reuse) & PSR-4 Namespaces

traits_demo.php
<?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);
?>
Execution Output:
[2026-08-21 17:30:00] LOG: Order #98765 successfully placed.

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

database_connection.php
<?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.

pdo_crud_operations.php
<?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.

bank_transfer_transaction.php
<?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.

strlen() Length & Search

Returns the length (number of bytes/characters) of a given string.

strlen(string $string): int
$str = "Shubh";
echo strlen($str); // Outputs: 5
str_word_count() Length & Search

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
strpos() Length & Search

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
stripos() Length & Search

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
str_contains()
PHP 8+ Length & Search

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)
str_starts_with()
PHP 8+ Length & Search

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)
strtolower() Case Manipulation

Converts all characters of a string to lowercase.

strtolower(string $string): string
$name = "SHUBH PATEL";
echo strtolower($name); // Outputs: shubh patel
strtoupper() Case Manipulation

Converts all characters of a string to uppercase.

strtoupper(string $string): string
$title = "php developer";
echo strtoupper($title); // Outputs: PHP DEVELOPER
ucfirst() & lcfirst() Case Manipulation

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
ucwords() Case Manipulation

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
str_replace() Replace & Modify

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
substr() Replace & Modify

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
strrev() & str_repeat() Replace & Modify

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: =-=-=-=-=-
explode() Split & Join

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 )
implode() / join() Split & Join

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
trim(), ltrim(), rtrim() Trim & Sanitize

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!'
htmlspecialchars() Trim & Sanitize

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: &lt;script&gt;alert('Hacked!');&lt;/script&gt;
str_pad() Trim & Sanitize

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:

php_repl_terminal
Live Evaluator