PHP logo

PHP Beginner

Server-side scripting language — built for the web, driving dynamic template generation, robust OOP frameworks, and secure APIs.

1 Variables & Output Tags

PHP execution begins inside the <?php tag boundary. Variables are prefixed with a $ character, dynamically typed, and statements require ending semicolons.

php · main.php
<?php
// Single-line comment
/* Multi-line comment block */

$domain = "vidux.sh"; 
$status = "Active";

// String concatenation uses the dot (.) operator
echo "System target: " . $domain; 

// Double quotes parse variables natively inside the text
echo "<p>Status metrics: {$status}</p>"; 

2 Core Types & Array Architectures

PHP fields encompass standard primitive metrics and complex multi-purpose arrays that can be structured as both indexed vectors and explicit associative dictionaries.

String Binary safe strings $name = 'testName';
Integer / Float Signed numbers / Floats $balance = -342.50;
Boolean Logical truths $auth = true;
Indexed Array Ordered standard vector ['HTML', 'CSS', 'PHP']
Associative Array Explicit Key-Value mapping ['id' => 42, 'db' => 'sql']
Null Explicit empty context $session = null;

3 Conditionals & Logical Blocks

Control processes via if-elseif-else or strict structures. Use identical evaluation symbols (===) to validate both content values and type matching.

php · conditional.php
$responseCode = 200;

if ($responseCode === 200) {
    echo "Operational success.";
} elseif ($responseCode >= 400 && $responseCode < 500) {
    echo "Client execution block mismatch error.";
} else {
    echo "Generic terminal fallback triggered.";
}

4 Loops & Foreach Keymaps

While standard for bounds execute predictably, foreach provides the cleanest interface for unpacking structural associative mappings safely.

php · loops.php
$logConfig = [
    "app_name" => "testName",
    "version"  => "1.0.4",
    "env"      => "production"
];

// Unpacking associative keys and matching values directly
foreach ($logConfig as $parameter => $setting) {
    echo "Setting up: {$parameter} assigned to {$setting}\n";
}

5 Functions & Type Hinting

Modern PHP strictly utilizes explicit scalar data type rules for parameters alongside enforced return signature mapping blocks.

php · functions.php
declare(strict_types=1); // Enforces strict type compliance matching

function generateTransactionId(string $prefix, int $entropy): string {
    $uniqueHash = md5((string)time() . $entropy);
    return $prefix . "_" . substr($uniqueHash, 0, 8);
}

$txId = generateTransactionId("TX", 9942);

6 Classes & Object Methods

PHP implements an Object-Oriented model featuring explicit visibility attributes (public, protected, private) alongside standard class definitions.

php · oop.php
class DatabaseConfig {
    private string $dsn;

    // PHP 8+ Constructor Property Promotion architectural shorthand
    public function __construct(private string $host, private int $port) {
        $this->dsn = "mysql:host=" . $this->host . ";port=" . $this->port;
    }

    public function getConnectionString(): string {
        return $this->dsn;
    }
}

$configInstance = new DatabaseConfig("127.0.0.1", 3306);
Always target instance members using the **arrow operator object syntax** ($this->property). Dropping the pointer format results in structural execution parsing failures.

7 Superglobals ($_GET, $_POST)

Superglobals are built-in arrays accessible everywhere regardless of scope. They contain incoming runtime client vectors like query strings or multi-part forms.

php · request.php
// Extracting safe attributes filtering raw input vectors manually
$userEmail = $_POST['email'] ?? null;

if ($userEmail !== null) {
    // Filter and sanitize string inputs securely before operating data
    $cleanEmail = filter_var($userEmail, FILTER_SANITIZE_EMAIL);
    
    if (filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)) {
        echo "Validated secure email parameter: " . htmlspecialchars($cleanEmail);
    }
}

8 Database Interactivity via PDO

PHP Data Objects (PDO) deliver a secure database abstraction layer. Always leverage **Prepared Statements** to entirely prevent SQL Injection exploits.

php · pdo.php
$pdoConnection = new PDO('mysql:host=localhost;dbname=testName', 'root', 'secret_pass', [
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION
]);

// Structuring parameterized placeholders
$queryStatement = $pdoConnection->prepare("SELECT id, username FROM users WHERE status = :status");
$queryStatement->execute(['status' => 'active']);

$allActiveUsers = $queryStatement->fetchAll();
With modern PHP fundamentals solid, your next scaling steps include building production architectures utilizing modern paradigms via MVC frameworks like **Laravel**.