A quick-reference instruction sheet covering the fundamentals of PHP programming.
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.
.php extension<?php ... ?> tags;//, #, or /* ... */<!-- index.php -->
<?php
// Single-line comment
# Also a single-line comment
/* Multi-line
comment */
echo "Hello, World!";
?>
<?php ?> tags is sent to the browser as-is.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"
?>
| Type | Example | Description |
|---|---|---|
string | "hello" | Text, in single or double quotes |
int | 42 | Whole numbers |
float | 3.14 | Decimal numbers |
bool | true / false | Boolean values |
null | null | No value |
array | [1, 2, 3] | Ordered collection |
object | new MyClass() | Instance of a class |
<?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
?>
<?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
?>
=== over == to avoid type coercion surprises.<?php
$a && $b // AND — true if both are true
$a || $b // OR — true if either is true
!$a // NOT — inverts the boolean
?>
<?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"
?>
<?php
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // apple
$fruits[] = "date"; // append
count($fruits); // 4
?>
<?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
?>
<?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
?>
<?php
$score = 75;
if ($score >= 90) {
echo "A";
} elseif ($score >= 75) {
echo "B";
} elseif ($score >= 60) {
echo "C";
} else {
echo "F";
}
?>
<?php
$day = "Mon";
switch ($day) {
case "Mon":
echo "Monday";
break;
case "Fri":
echo "Friday";
break;
default:
echo "Other day";
}
?>
<?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";
?>
<?php
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
// Output: 12345
?>
<?php
for ($i = 0; $i < 5; $i++) {
echo $i . " ";
}
// Output: 0 1 2 3 4
?>
<?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>";
}
?>
break to exit a loop early, and continue to skip to the next iteration.<?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
?>
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!";
}
}
?>
htmlspecialchars() to prevent XSS, and never trust $_GET / $_POST values directly in SQL queries — use prepared statements instead.<?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!
?>
| Visibility | Accessible from |
|---|---|
public | Anywhere |
protected | Class itself and subclasses |
private | Class itself only |