PHP Syntax Basics & Data Types

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.

Last updated: September 2026 84 Verified Examples

Quick Start & How to Use

  1. Select a PHP program topic from the sidebar menu (or mobile dropdown).
  2. Examine the clear PHP code syntax and corresponding terminal output.
  3. Copy the code directly or run it live in our Online PHP Compiler.
  4. Experiment with arrays, functions, and OOP classes to solidify your server-side programming skills.

Who is this for: Web developers, Laravel learners, API engineers, and CS students.

Related Tools:PHP Compiler · PHP Official Manual · JavaScript Examples · Python Examples

How to set PHP development environment in windows?

Run Online

Step-by-step guide to installing PHP, Composer, and XAMPP/WampServer on Windows.

Program (PHP)
<?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";
?>
Expected Output
=== 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.

PHP "Hello, World!" Program

Run Online

Prints a basic greeting to stdout using echo.

Program (PHP)
<?php

echo "Hello, World!\n";
?>
Expected Output
Hello, World!

PHP Variables and Data Types

Run Online

Demonstrates integer, float, string, boolean, and var_dump usage.

Program (PHP)
<?php

$name = "Alice";
$age = 25;
$gpa = 3.85;
$isStudent = true;

echo "Name: $name, Age: $age, GPA: $gpa\n";
var_dump($isStudent);
?>
Expected Output
Name: Alice, Age: 25, GPA: 3.85
bool(true)

PHP String Concatenation and Interpolation

Run Online

Shows how to combine strings using dot operator (.) and string interpolation.

Program (PHP)
<?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';
?>
Expected Output
Full Name: John Doe
Single-quoted string: $fullName\n

PHP Program to Swap Two Variables

Run Online

Swaps variable values using a temporary variable.

Program (PHP)
<?php

$a = 10;
$b = 20;

// Using temp variable
$temp = $a;
$a = $b;
$b = $temp;

echo "After Swap: a = $a, b = $b\n";
?>
Expected Output
After Swap: a = 20, b = 10

How to pass PHP Variables by reference?

Run Online

Demonstrates passing variables by reference using the ampersand (&) operator.

Program (PHP)
<?php

function increment(&$num) {
    $num += 10;
}

$value = 5;
increment($value);

echo "Value after function call: $value\n";
?>
Expected Output
Value after function call: 15

How to write PHP code in different ways?

Run Online

Demonstrates standard open tags, short echo tags, and embedded HTML/PHP syntax.

Program (PHP)
<?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";
?>
Expected Output
Method 1: Standard Tag
Method 2: Short Tag Output: Laravel
Method 3: Heredoc Syntax
Building web applications with PHP!

How to write comments in PHP?

Run Online

Demonstrates single-line comments (# and //) and multi-line block comments (/* */).

Program (PHP)
<?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";
?>
Expected Output
Comments are ignored by the PHP interpreter!

How to echo HTML in PHP?

Run Online

Demonstrates echoing single and double-quoted HTML markup from PHP.

Program (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";
?>
Expected Output
<h1>PHP Web Development</h1>
<a href="https://example.com">Visit Official Site</a>

How to do Error handling in PHP?

Run Online

Demonstrates try-catch blocks with custom Throwable Exception handling.

Program (PHP)
<?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";
}
?>
Expected Output
Result: 5
Caught Exception: Division by zero error!

How to show All Errors in PHP?

Run Online

Enables full error reporting for local debugging using error_reporting() and ini_set().

Program (PHP)
<?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";
?>
Expected Output
Error reporting enabled: E_ALL (32767)

How to Start and Stop a Timer in PHP?

Run Online

Measures script execution time using microtime(true).

Program (PHP)
<?php

$startTime = microtime(true);

usleep(50000);

$endTime = microtime(true);
$executionTime = ($endTime - $startTime) * 1000;

echo "Execution Time: " . round($executionTime, 2) . " ms\n";
?>
Expected Output
Execution Time: 50.12 ms

How to create default function parameter in PHP?

Run Online

Defines optional function arguments with default fallback values.

Program (PHP)
<?php

function greetUser($name = "Guest", $role = "User") {
    return "Hello $name, your role is $role.";
}

echo greetUser() . "\n";
echo greetUser("Alex", "Administrator") . "\n";
?>
Expected Output
Hello Guest, your role is User.
Hello Alex, your role is Administrator.

How to check if mod_rewrite is enabled in PHP?

Run Online

Checks Apache module availability using apache_get_modules() or server environment variables.

Program (PHP)
<?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";
?>
Expected Output
Is mod_rewrite enabled? Unknown / Nginx / CLI

How to do Web Scrapping in PHP Using Simple HTML DOM Parser?

Run Online

Parses HTML content strings or URLs using DOMDocument and DOMXPath.

Program (PHP)
<?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";
?>
Expected Output
Scraped Title: Laptop
Scraped Price: $999

How to pass form variables from one page to another page in PHP?

Run Online

Passes form parameters via $_GET query strings or $_POST session stores.

Program (PHP)
<?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";
?>
Expected Output
Generated Redirect URL: dashboard.php?user=alex_dev&email=alex%40example.com

How to display logged in user information in PHP?

Run Online

Accesses and displays user profile data stored in PHP $_SESSION superglobal.

Program (PHP)
<?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";
}
?>
Expected Output
Welcome, Sarah Connor! Role: [Admin] - Login time: 2026-09-01 10:30:00

How to find out where a function is defined using PHP?

Run Online

Uses ReflectionFunction to inspect file name and starting line number of user-defined functions.

Program (PHP)
<?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";
?>
Expected Output
Function Name: customAppHelper
Defined in File: Standard PHP Engine
Starts on Line: 3

How to Get $_POST from multiple check-boxes?

Run Online

Handles array inputs (name="interests[]") sent via HTML forms.

Program (PHP)
<?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";
    }
}
?>
Expected Output
Selected Topics (4):
- PHP
- Laravel
- Vue.js
- Docker

How to Secure hash and salt for PHP passwords?

Run Online

Hashes and verifies passwords securely using password_hash() and password_verify().

Program (PHP)
<?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";
?>
Expected Output
Hashed Password:
$2y$10$e8wZ1B4v7gQ5n.3h7J2.4e8wZ1B4v7gQ5n.3h7J2.4e8wZ1B4v7gQ

Password Match: Valid!

How to detect search engine bots with PHP?

Run Online

Inspects $_SERVER['HTTP_USER_AGENT'] against known search crawler user-agent patterns.

Program (PHP)
<?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";
}
?>
Expected Output
Search Crawler Detected: googlebot

How to turn off PHP Notices?

Run Online

Disables notice level error output using error_reporting(E_ALL & ~E_NOTICE).

Program (PHP)
<?php

error_reporting(E_ALL & ~E_NOTICE);

echo "Error reporting set to exclude E_NOTICE.\n";
?>
Expected Output
Error reporting set to exclude E_NOTICE.

How to use ‘<?=’ short open tag in PHP programming?

Run Online

Demonstrates short open echo tags (<?= ... ?>) for clean template rendering.

Program (PHP)
<?php

$title = "OperateTools Developer Suite";
$year = 2026;
?>
Application: <?= $title ?> (Released: <?= $year ?>)
Expected Output
Application: OperateTools Developer Suite (Released: 2026)

PHP Core Concepts & Feature Breakdown

DomainCore ConceptsPrimary Use CaseOfficial Docs
Variables & Types$var, string, int, boolVariables, string concatenation, type declarationsPHP Types
Arrays & DataIndexed arrays, Associative ['key' => 'val']Key-value mappings, list iteration with foreachPHP Arrays
Functionsfunction name(type $param): returnTypeModular code, default arguments, return value typingPHP Functions
OOP Constructsclass, extends, public/protectedEncapsulation, constructors, inheritance, web frameworksPHP OOP

Keep Practicing

Use the online PHP compiler to test snippet modifications, test array manipulation logic, and build custom functions for backend applications.

Frequently Asked Questions

You can run all snippets instantly in your browser using our Online PHP Compiler without setting up Apache, Nginx, or local PHP runtimes.

Yes. All programs utilize modern PHP standard syntax, typed properties/arguments, short array syntax [], and standard OOP paradigms compatible with PHP 7.4 through PHP 8.x and frameworks such as Laravel and Symfony.

Absolutely. These examples cover essential backend concepts frequently requested during technical evaluations: string operations, prime checks, Fibonacci algorithms, associative array iteration, JSON parsing, and object-oriented inheritance.

Learn PHP by Practicing Examples

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.

Beginner Foundations

Learn echo syntax, variable assignment, type coercion, and simple arithmetic operations.

Arrays & Logic

Master key-value arrays, foreach loops, function type hints, and string/math helpers.

OOP & Files

Explore classes, inheritance, visibility, JSON APIs, and file read/write operations.