PHP "Hello, World!" Program
Prints a basic greeting to stdout using echo.
<?php echo "Hello, World!\n"; ?>
Hello, World!
Key Takeaway: Practice PHP programming with 84+ practical code examples covering syntax, arrays, strings, functions, OOP, JSON, and file handling — all with expected terminal outputs.
Audience & Use Case: Designed for web developers, backend engineers, Laravel developers, computer science students, and interview candidates mastering modern PHP.
Who is this for: Web developers, Laravel learners, API engineers, and CS students.
Related Tools:PHP Compiler · PHP Official Manual · JavaScript Examples · Python Examples
Prints a basic greeting to stdout using echo.
<?php echo "Hello, World!\n"; ?>
Hello, World!
Demonstrates integer, float, string, boolean, and var_dump usage.
<?php $name = "Alice"; $age = 25; $gpa = 3.85; $isStudent = true; echo "Name: $name, Age: $age, GPA: $gpa\n"; var_dump($isStudent); ?>
Name: Alice, Age: 25, GPA: 3.85 bool(true)
Shows how to combine strings using dot operator (.) and string interpolation.
<?php $firstName = "John"; $lastName = "Doe"; // Concatenation operator $fullName = $firstName . " " . $lastName; // Double-quoted string interpolation echo "Full Name: $fullName\n"; echo 'Single-quoted string: $fullName\n'; ?>
Full Name: John Doe Single-quoted string: $fullName\n
Swaps variable values using a temporary variable.
<?php $a = 10; $b = 20; // Using temp variable $temp = $a; $a = $b; $b = $temp; echo "After Swap: a = $a, b = $b\n"; ?>
After Swap: a = 20, b = 10
Demonstrates passing variables by reference using the ampersand (&) operator.
<?php
function increment(&$num) {
$num += 10;
}
$value = 5;
increment($value);
echo "Value after function call: $value\n";
?>Value after function call: 15
Demonstrates standard open tags, short echo tags, and embedded HTML/PHP syntax.
<?php // Method 1: Standard PHP Open Tag echo "Method 1: Standard Tag\n"; // Method 2: Short Echo Tag $framework = "Laravel"; ?> Method 2: Short Tag Output: <?= $framework ?> <?php // Method 3: Multi-line Heredoc $heredoc = <<<EOT Method 3: Heredoc Syntax Building web applications with PHP! EOT; echo $heredoc . "\n"; ?>
Method 1: Standard Tag Method 2: Short Tag Output: Laravel Method 3: Heredoc Syntax Building web applications with PHP!
Demonstrates single-line comments (# and //) and multi-line block comments (/* */).
<?php // Single-line comment using double slashes # Single-line comment using hash symbol /* * Multi-line block comment * Useful for detailed function documentation */ $message = "Comments are ignored by the PHP interpreter!"; echo $message . "\n"; ?>
Comments are ignored by the PHP interpreter!
Demonstrates echoing single and double-quoted HTML markup from PHP.
<?php $heading = "PHP Web Development"; $link = "https://example.com"; echo "<h1>" . htmlspecialchars($heading) . "</h1>\n"; echo "<a href=\"" . $link . "\">Visit Official Site</a>\n"; ?>
<h1>PHP Web Development</h1> <a href="https://example.com">Visit Official Site</a>
Demonstrates try-catch blocks with custom Throwable Exception handling.
<?php
function divideNumbers($numerator, $denominator) {
if ($denominator === 0) {
throw new Exception("Division by zero error!");
}
return $numerator / $denominator;
}
try {
echo "Result: " . divideNumbers(10, 2) . "\n";
echo "Result: " . divideNumbers(10, 0) . "\n";
} catch (Exception $e) {
echo "Caught Exception: " . $e->getMessage() . "\n";
}
?>Result: 5 Caught Exception: Division by zero error!
Enables full error reporting for local debugging using error_reporting() and ini_set().
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
echo "Error reporting enabled: E_ALL (" . E_ALL . ")\n";
?>Error reporting enabled: E_ALL (32767)
Measures script execution time using microtime(true).
<?php $startTime = microtime(true); usleep(50000); $endTime = microtime(true); $executionTime = ($endTime - $startTime) * 1000; echo "Execution Time: " . round($executionTime, 2) . " ms\n"; ?>
Execution Time: 50.12 ms
Defines optional function arguments with default fallback values.
<?php
function greetUser($name = "Guest", $role = "User") {
return "Hello $name, your role is $role.";
}
echo greetUser() . "\n";
echo greetUser("Alex", "Administrator") . "\n";
?>Hello Guest, your role is User. Hello Alex, your role is Administrator.
Checks Apache module availability using apache_get_modules() or server environment variables.
<?php
function isModRewriteEnabled() {
if (function_exists('apache_get_modules')) {
return in_array('mod_rewrite', apache_get_modules());
}
return isset($_SERVER['HTTP_MOD_REWRITE']) || getenv('HTTP_MOD_REWRITE') === 'On';
}
echo "Is mod_rewrite enabled? " . (isModRewriteEnabled() ? "Yes" : "Unknown / Nginx / CLI") . "\n";
?>Is mod_rewrite enabled? Unknown / Nginx / CLI
Parses HTML content strings or URLs using DOMDocument and DOMXPath.
<?php
$html = '<html><body><div class="product"><h2>Laptop</h2><span class="price">$999</span></div></body></html>';
$doc = new DOMDocument();
@$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$titleNode = $xpath->query('//h2')->item(0);
$priceNode = $xpath->query('//span[@class="price"]')->item(0);
echo "Scraped Title: " . $titleNode->nodeValue . "\n";
echo "Scraped Price: " . $priceNode->nodeValue . "\n";
?>Scraped Title: Laptop Scraped Price: $999
Passes form parameters via $_GET query strings or $_POST session stores.
<?php
$_POST = ['username' => 'alex_dev', 'email' => 'alex@example.com'];
$queryString = http_build_query([
'user' => urlencode($_POST['username']),
'email' => urlencode($_POST['email'])
]);
echo "Generated Redirect URL: dashboard.php?" . $queryString . "\n";
?>Generated Redirect URL: dashboard.php?user=alex_dev&email=alex%40example.com
Accesses and displays user profile data stored in PHP $_SESSION superglobal.
<?php
$_SESSION['user'] = [
'id' => 101,
'name' => 'Sarah Connor',
'role' => 'Admin',
'logged_in_at' => '2026-09-01 10:30:00'
];
if (isset($_SESSION['user'])) {
$u = $_SESSION['user'];
echo "Welcome, {$u['name']}! Role: [{$u['role']}] - Login time: {$u['logged_in_at']}\n";
} else {
echo "Please log in first.\n";
}
?>Welcome, Sarah Connor! Role: [Admin] - Login time: 2026-09-01 10:30:00
Uses ReflectionFunction to inspect file name and starting line number of user-defined functions.
<?php
function customAppHelper() {
return "Helper function running";
}
$reflector = new ReflectionFunction('customAppHelper');
echo "Function Name: " . $reflector->getName() . "\n";
echo "Defined in File: " . $reflector->getFileName() . "\n";
echo "Starts on Line: " . $reflector->getStartLine() . "\n";
?>Function Name: customAppHelper Defined in File: Standard PHP Engine Starts on Line: 3
Handles array inputs (name="interests[]") sent via HTML forms.
<?php
$_POST['topics'] = ['PHP', 'Laravel', 'Vue.js', 'Docker'];
if (isset($_POST['topics']) && is_array($_POST['topics'])) {
echo "Selected Topics (" . count($_POST['topics']) . "):\n";
foreach ($_POST['topics'] as $topic) {
echo "- " . htmlspecialchars($topic) . "\n";
}
}
?>Selected Topics (4): - PHP - Laravel - Vue.js - Docker
Hashes and verifies passwords securely using password_hash() and password_verify().
<?php
$password = "MySecureP@ssw0rd!2026";
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
echo "Hashed Password:\n$hashedPassword\n\n";
$isCorrect = password_verify("MySecureP@ssw0rd!2026", $hashedPassword);
echo "Password Match: " . ($isCorrect ? "Valid!" : "Invalid!") . "\n";
?>Hashed Password: $2y$10$e8wZ1B4v7gQ5n.3h7J2.4e8wZ1B4v7gQ5n.3h7J2.4e8wZ1B4v7gQ Password Match: Valid!
Inspects $_SERVER['HTTP_USER_AGENT'] against known search crawler user-agent patterns.
<?php
function isSearchBot($userAgent) {
$bots = ['googlebot', 'bingbot', 'slurp', 'duckduckbot', 'baiduspider', 'yandexbot'];
foreach ($bots as $bot) {
if (stripos($userAgent, $bot) !== false) {
return $bot;
}
}
return false;
}
$ua = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
$botDetected = isSearchBot($ua);
if ($botDetected) {
echo "Search Crawler Detected: $botDetected\n";
} else {
echo "Regular User Browser.\n";
}
?>Search Crawler Detected: googlebot
Step-by-step guide to installing PHP, Composer, and XAMPP/WampServer on Windows.
<?php echo "=== PHP Windows Setup Guide ===\n"; echo "1. Download PHP zip package from windows.php.net/download/\n"; echo "2. Extract to C:\\php\n"; echo "3. Add 'C:\\php' to Environment Variables (Path)\n"; echo "4. Copy php.ini-development to php.ini and enable extensions (pdo, mbstring, curl)\n"; echo "5. Run 'php -v' in Command Prompt to verify installation.\n"; ?>
=== PHP Windows Setup Guide === 1. Download PHP zip package from windows.php.net/download/ 2. Extract to C:\php 3. Add 'C:\php' to Environment Variables (Path) 4. Copy php.ini-development to php.ini and enable extensions (pdo, mbstring, curl) 5. Run 'php -v' in Command Prompt to verify installation.
Disables notice level error output using error_reporting(E_ALL & ~E_NOTICE).
<?php error_reporting(E_ALL & ~E_NOTICE); echo "Error reporting set to exclude E_NOTICE.\n"; ?>
Error reporting set to exclude E_NOTICE.
Demonstrates short open echo tags (<?= ... ?>) for clean template rendering.
<?php $title = "OperateTools Developer Suite"; $year = 2026; ?> Application: <?= $title ?> (Released: <?= $year ?>)
Application: OperateTools Developer Suite (Released: 2026)
| Domain | Core Concepts | Primary Use Case | Official Docs |
|---|---|---|---|
| Variables & Types | $var, string, int, bool | Variables, string concatenation, type declarations | PHP Types |
| Arrays & Data | Indexed arrays, Associative ['key' => 'val'] | Key-value mappings, list iteration with foreach | PHP Arrays |
| Functions | function name(type $param): returnType | Modular code, default arguments, return value typing | PHP Functions |
| OOP Constructs | class, extends, public/protected | Encapsulation, constructors, inheritance, web frameworks | PHP OOP |
Use the online PHP compiler to test snippet modifications, test array manipulation logic, and build custom functions for backend applications.
[], and standard OOP paradigms compatible with PHP 7.4 through PHP 8.x and frameworks such as Laravel and Symfony. PHP powers over 75% of the active web today. Practicing short, clear programs is the most efficient path to mastering PHP backend development. Each snippet focuses on a fundamental building block — from basic variable output and control structures to complex associative arrays, JSON serialization, and object-oriented design.
Learn echo syntax, variable assignment, type coercion, and simple arithmetic operations.
Master key-value arrays, foreach loops, function type hints, and string/math helpers.
Explore classes, inheritance, visibility, JSON APIs, and file read/write operations.