Back to PHP Examples

Basic PHP

A quick-reference instruction sheet covering the fundamentals of PHP programming.

Contents

  1. What is PHP?
  2. Syntax & Structure
  3. Variables & Data Types
  4. Operators
  5. Strings
  6. Arrays
  7. Control Structures
  8. Loops
  9. Functions
  10. Forms & User Input
  11. Intro to OOP

1. What is PHP?

PHP (PHP: Hypertext Preprocessor) is a server-side scripting language designed for web development. PHP code runs on the server and outputs HTML to the browser.

2. Syntax & Structure

<!-- index.php -->
<?php
    // Single-line comment
    # Also a single-line comment
    /* Multi-line
       comment */

    echo "Hello, World!";
?>
PHP can be mixed with HTML. Anything outside <?php ?> tags is sent to the browser as-is.

3. Variables & Data Types

Variables start with $ and do not need a declared type.

<?php
$name    = "Alice";      // String
$age     = 30;           // Integer
$price   = 9.99;         // Float
$active  = true;         // Boolean
$nothing = null;         // Null

echo $name;               // Alice
var_dump($age);           // int(30)
gettype($price);          // "double"
?>
TypeExampleDescription
string"hello"Text, in single or double quotes
int42Whole numbers
float3.14Decimal numbers
booltrue / falseBoolean values
nullnullNo value
array[1, 2, 3]Ordered collection
objectnew MyClass()Instance of a class

4. Operators

Arithmetic

<?php
$a = 10; $b = 3;
echo $a + $b;   // 13  — addition
echo $a - $b;   // 7   — subtraction
echo $a * $b;   // 30  — multiplication
echo $a / $b;   // 3.33 — division
echo $a % $b;   // 1   — modulus (remainder)
echo $a ** $b;  // 1000 — exponentiation
?>

Comparison

<?php
$x ==  $y   // Equal (value only)
$x === $y   // Identical (value AND type)
$x !=  $y   // Not equal
$x !== $y   // Not identical
$x <   $y   // Less than
$x >   $y   // Greater than
$x <=  $y   // Less than or equal
$x >=  $y   // Greater than or equal
?>
Always prefer === over == to avoid type coercion surprises.

Logical

<?php
$a && $b   // AND — true if both are true
$a || $b   // OR  — true if either is true
!$a        // NOT — inverts the boolean
?>

5. Strings

<?php
$first = "Alice";
$last  = "Smith";

// Concatenation uses the dot operator
echo $first . " " . $last;   // Alice Smith

// Variable interpolation (double quotes only)
echo "Hello, $first!";        // Hello, Alice!
echo "Hello, {$first}!";      // Same, clearer syntax

// Common string functions
strlen("hello");              // 5
strtoupper("hello");          // HELLO
strtolower("HELLO");          // hello
trim("  hello  ");           // "hello"
str_replace("o", "0", "foo"); // "f00"
substr("hello", 1, 3);        // "ell"
strpos("hello", "l");         // 2 (first occurrence)
explode(",", "a,b,c");        // ["a","b","c"]
implode("-", ["a","b"]);      // "a-b"
?>

6. Arrays

Indexed Arrays

<?php
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0];              // apple
$fruits[] = "date";          // append
count($fruits);              // 4
?>

Associative Arrays

<?php
$person = [
    "name" => "Alice",
    "age"  => 30,
    "city" => "NYC",
];

echo $person["name"];         // Alice
$person["email"] = "a@b.com"; // add key
array_keys($person);         // ["name","age","city","email"]
array_values($person);       // ["Alice",30,"NYC","a@b.com"]
array_key_exists("age", $person); // true
?>

Useful Array Functions

<?php
sort($arr);                   // sort indexed array ascending
rsort($arr);                  // sort descending
asort($arr);                  // sort assoc by value
ksort($arr);                  // sort assoc by key
in_array("apple", $fruits);  // true
array_push($arr, "x");        // append
array_pop($arr);              // remove last
array_merge($a, $b);         // merge two arrays
array_slice($arr, 1, 3);      // extract sub-array
?>

7. Control Structures

if / elseif / else

<?php
$score = 75;

if ($score >= 90) {
    echo "A";
} elseif ($score >= 75) {
    echo "B";
} elseif ($score >= 60) {
    echo "C";
} else {
    echo "F";
}
?>

switch

<?php
$day = "Mon";

switch ($day) {
    case "Mon":
        echo "Monday";
        break;
    case "Fri":
        echo "Friday";
        break;
    default:
        echo "Other day";
}
?>

Ternary & Null Coalescing

<?php
// Ternary: condition ? if_true : if_false
$status = $age >= 18 ? "adult" : "minor";

// Null coalescing: use right side if left is null/unset
$name = $_GET["name"] ?? "Guest";
?>

8. Loops

while

<?php
$i = 1;
while ($i <= 5) {
    echo $i;
    $i++;
}
// Output: 12345
?>

for

<?php
for ($i = 0; $i < 5; $i++) {
    echo $i . " ";
}
// Output: 0 1 2 3 4
?>

foreach (great for arrays)

<?php
$fruits = ["apple", "banana", "cherry"];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

// With key => value for associative arrays
$person = ["name" => "Alice", "age" => 30];
foreach ($person as $key => $value) {
    echo "$key: $value<br>";
}
?>
Use break to exit a loop early, and continue to skip to the next iteration.

9. Functions

<?php
// Basic function
function greet($name) {
    return "Hello, $name!";
}
echo greet("Alice");          // Hello, Alice!

// Default parameter values
function greet($name = "World") {
    return "Hello, $name!";
}
echo greet();                 // Hello, World!

// Type hints (PHP 7+)
function add(int $a, int $b): int {
    return $a + $b;
}

// Variadic functions (variable number of args)
function sum(...$nums) {
    return array_sum($nums);
}
echo sum(1, 2, 3, 4);         // 10
?>

10. Forms & User Input

PHP reads form data via the superglobals $_GET, $_POST, and $_REQUEST.

<!-- form.html -->
<form method="post" action="process.php">
    <input type="text" name="username">
    <input type="submit" value="Submit">
</form>
<!-- process.php -->
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Always sanitize user input!
    $username = htmlspecialchars(trim($_POST["username"] ?? ""));

    if (empty($username)) {
        echo "Username is required.";
    } else {
        echo "Welcome, $username!";
    }
}
?>
Always sanitize and validate user input. Use htmlspecialchars() to prevent XSS, and never trust $_GET / $_POST values directly in SQL queries — use prepared statements instead.

11. Intro to OOP

<?php
class Animal {
    // Properties
    public string $name;
    protected int $age;
    private string $secret = "hidden";

    // Constructor
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age  = $age;
    }

    // Method
    public function describe(): string {
        return "{$this->name} is {$this->age} years old.";
    }
}

// Inheritance
class Dog extends Animal {
    public function speak(): string {
        return $this->name . " says: Woof!";
    }
}

$dog = new Dog("Rex", 4);
echo $dog->describe();          // Rex is 4 years old.
echo $dog->speak();             // Rex says: Woof!
?>
VisibilityAccessible from
publicAnywhere
protectedClass itself and subclasses
privateClass itself only