Back to PHP tutorials
Basic16 min read

PHP Fundamentals

Learn PHP syntax, variables, operators, and control structures for server-side web development.

PHP Syntax and Output

PHP code lives in <?php ... ?> tags within HTML or standalone scripts. Statements end with semicolons. echo and print output strings; var_dump aids debugging types and values.

PHP runs on the server, generating HTML sent to browsers. Configure php.ini for development versus production error display.

Use short open tags only when deployment guarantees them enabled—standard tags maximize portability.

  • Enable declare(strict_types=1) in new files
  • Never expose display_errors in production
  • Use PHP 8.2+ for performance and language features
<?php
declare(strict_types=1);

$name = 'World';
echo "Hello, {$name}!\n";

Variables and Types

Variables start with $ and adopt types at runtime: string, int, float, bool, array, object, null. Type juggling occurs in loose comparisons—prefer === strict equality.

Null coalescing ?? and nullsafe ?-> operators reduce boilerplate for optional values.

Scalar type hints and return types on functions catch bugs early when strict_types is enabled.

  • Name variables descriptively in camelCase or snake_case consistently
  • Avoid global variables; pass dependencies explicitly
  • Use const for class constants, readonly for immutable properties
$count = 42;
$items = ['apple', 'banana'];
$user = null;
$email = $user?->getEmail() ?? 'guest@example.com';

Control Flow and Functions

if/elseif/else, switch with match expressions in PHP 8, foreach for arrays, while and for loops handle iteration. break and continue work as expected.

Define functions with optional defaults and typed parameters. Anonymous functions (closures) capture variables with use ($var).

Include require_once for loading files; autoloading via Composer replaces manual includes in modern apps.

  • Prefer match over switch when returning values
  • Extract repeated logic into pure functions
  • Document thrown exceptions on public functions
$status = match ($code) {
    200 => 'ok',
    404 => 'not found',
    default => 'error',
};

Get In Touch


Ready to discuss your next project? Drop me a message.