Learn PHP in 10 minutes
PHP is a widely-used, server-side scripting language designed for web development. Originally created for “Personal Home Pages,” PHP now stands for “PHP: Hypertext Preprocessor.” This tutorial covers PHP 8.3+ features, helping you quickly learn modern PHP development.
1. Writing Your First PHP Program
Let’s start with a simple program. Create a file named hello.php
and enter the following code:
<?php
echo "Hello, World!";
?>
Save the file and run it using a web server or PHP CLI:
php hello.php
The output will be:
Hello, World!
This simple program demonstrates PHP’s basic output functionality. The echo
statement is used to display text. PHP code is enclosed within <?php
and ?>
tags.
2. Basic Syntax
PHP syntax is straightforward and similar to C and Perl. PHP code is executed on the server, and the results are sent to the browser as plain HTML.
<?php
// This is a single-line comment
echo "Hello, World!";
/*
This is a multi-line comment
spanning multiple lines
*/
?>
Basic syntax rules in PHP:
- PHP Tags: PHP code must be enclosed in
<?php ... ?>
tags - Comments: Single-line comments use
//
or#
, multi-line comments use/* ... */
- Statements: End with semicolon
;
- Case Sensitivity: Variable names are case-sensitive, but function names are not
- Variables: Start with
$
symbol
<?php
$name = "John"; // Variable (case-sensitive)
$Name = "Jane"; // Different variable
echo $name; // Outputs: John
ECHO $Name; // Outputs: Jane (ECHO works same as echo)
?>
3. Variables and Data Types
In PHP, variables are containers for storing data. PHP is a loosely typed language, meaning you don’t need to declare variable types explicitly.
Variable naming rules:
- Must start with
$
symbol - Can contain letters, numbers, and underscores
- Cannot start with a number
- Case-sensitive
PHP’s main data types:
- String: Text data enclosed in quotes
- Integer: Whole numbers
- Float: Decimal numbers
- Boolean:
true
orfalse
- Array: Collection of values
- Object: Instance of a class
- NULL: Represents no value
- Resource: Reference to external resources
<?php
$name = "Alice"; // String
$age = 25; // Integer
$height = 5.8; // Float
$is_student = true; // Boolean
$grades = [90, 85, 92]; // Array
$data = null; // NULL
// Type checking
var_dump($name); // string(5) "Alice"
echo gettype($age); // integer
?>
3.1 String Operations
Strings can be defined using single or double quotes, with different behaviors:
<?php
$single = 'Single quote string';
$double = "Double quote string";
$name = "John";
$greeting = "Hello, $name!"; // Variable interpolation
$greeting2 = 'Hello, $name!'; // No interpolation
echo $greeting; // Hello, John!
echo $greeting2; // Hello, $name!
// String concatenation
$full_name = "John" . " " . "Doe";
$full_name .= " Jr."; // Append
// String functions
echo strlen($name); // String length: 4
echo strtoupper($name); // JOHN
echo strtolower($name); // john
echo substr($name, 0, 2); // Jo
?>
3.2 Arrays
PHP supports indexed arrays, associative arrays, and multidimensional arrays:
<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5);
// Associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
// Multidimensional array
$students = [
["name" => "Alice", "grade" => 90],
["name" => "Bob", "grade" => 85],
["name" => "Carol", "grade" => 92]
];
// Accessing arrays
echo $fruits[0]; // apple
echo $person["name"]; // John
echo $students[0]["grade"]; // 90
// Array functions
echo count($fruits); // 3
array_push($fruits, "grape"); // Add element
print_r($fruits); // Display array
?>
4. Operators
PHP provides various operators for different operations:
4.1 Arithmetic Operators
<?php
$a = 10;
$b = 3;
echo $a + $b; // Addition: 13
echo $a - $b; // Subtraction: 7
echo $a * $b; // Multiplication: 30
echo $a / $b; // Division: 3.333...
echo $a % $b; // Modulus: 1
echo $a ** $b; // Exponentiation: 1000
?>
4.2 Comparison Operators
<?php
$x = 5;
$y = "5";
var_dump($x == $y); // true (equal value)
var_dump($x === $y); // false (identical type and value)
var_dump($x != $y); // false
var_dump($x !== $y); // true
var_dump($x > 3); // true
var_dump($x <= 5); // true
?>
4.3 Logical Operators
<?php
$a = true;
$b = false;
var_dump($a && $b); // false (AND)
var_dump($a || $b); // true (OR)
var_dump(!$a); // false (NOT)
var_dump($a and $b); // false (AND, lower precedence)
var_dump($a or $b); // true (OR, lower precedence)
?>
5. Control Flow
5.1 if Statements
<?php
$age = 20;
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
}
// Ternary operator
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
?>
5.2 switch Statements
<?php
$day = "Monday";
switch ($day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
echo "Weekday";
break;
case "Saturday":
case "Sunday":
echo "Weekend";
break;
default:
echo "Invalid day";
}
?>
5.3 Loops
for Loop:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i\n";
}
// foreach for arrays
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// foreach with key-value pairs
$person = ["name" => "John", "age" => 30];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>
while and do-while Loops:
<?php
$count = 0;
while ($count < 3) {
echo "Count: $count\n";
$count++;
}
$num = 0;
do {
echo "Number: $num\n";
$num++;
} while ($num < 3);
?>
6. Functions
Functions in PHP are reusable blocks of code that perform specific tasks:
<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
// Function with default parameters
function calculate_area($length, $width = 1) {
return $length * $width;
}
echo calculate_area(5); // 5 (width defaults to 1)
echo calculate_area(5, 3); // 15
// Variable arguments
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10
// Anonymous functions (closures)
$multiply = function($a, $b) {
return $a * $b;
};
echo $multiply(4, 5); // 20
?>
6.1 Variable Scope
<?php
$global_var = "I'm global";
function test_scope() {
global $global_var;
$local_var = "I'm local";
echo $global_var; // Accessible with 'global' keyword
echo $local_var; // Local to this function
}
test_scope();
// Static variables
function counter() {
static $count = 0;
$count++;
echo "Count: $count\n";
}
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
?>
7. Object-Oriented Programming
PHP supports object-oriented programming with classes and objects:
<?php
class Person {
// Properties
private $name;
private $age;
public $city;
// Constructor
public function __construct($name, $age, $city = "Unknown") {
$this->name = $name;
$this->age = $age;
$this->city = $city;
}
// Methods
public function getName() {
return $this->name;
}
public function setAge($age) {
if ($age > 0) {
$this->age = $age;
}
}
public function getAge() {
return $this->age;
}
public function introduce() {
return "Hi, I'm {$this->name}, {$this->age} years old from {$this->city}";
}
}
// Creating objects
$person1 = new Person("John", 25, "New York");
$person2 = new Person("Jane", 30);
echo $person1->introduce();
echo $person2->getName();
?>
7.1 Inheritance
<?php
class Animal {
protected $name;
protected $species;
public function __construct($name, $species) {
$this->name = $name;
$this->species = $species;
}
public function makeSound() {
return "{$this->name} makes a sound";
}
public function getInfo() {
return "{$this->name} is a {$this->species}";
}
}
class Dog extends Animal {
private $breed;
public function __construct($name, $breed) {
parent::__construct($name, "Dog");
$this->breed = $breed;
}
public function makeSound() {
return "{$this->name} barks";
}
public function fetch() {
return "{$this->name} fetches the ball";
}
}
$dog = new Dog("Buddy", "Golden Retriever");
echo $dog->getInfo(); // Buddy is a Dog
echo $dog->makeSound(); // Buddy barks
echo $dog->fetch(); // Buddy fetches the ball
?>
8. Error Handling
PHP provides several ways to handle errors and exceptions:
<?php
// Try-catch for exceptions
try {
$result = 10 / 0;
throw new Exception("Custom error message");
} catch (DivisionByZeroError $e) {
echo "Division by zero error: " . $e->getMessage();
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
} finally {
echo "This always executes";
}
// Custom exception class
class CustomException extends Exception {
public function errorMessage() {
return "Custom error on line {$this->getLine()} in {$this->getFile()}: {$this->getMessage()}";
}
}
try {
throw new CustomException("Something went wrong!");
} catch (CustomException $e) {
echo $e->errorMessage();
}
?>
9. File Operations
PHP provides various functions for file manipulation:
<?php
// Reading files
$content = file_get_contents("example.txt");
echo $content;
// Writing files
file_put_contents("output.txt", "Hello, PHP!");
// File operations with error handling
if (file_exists("data.txt")) {
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
echo $line . "\n";
}
} else {
echo "File not found";
}
// Working with file handles
$handle = fopen("log.txt", "a");
if ($handle) {
fwrite($handle, "Log entry: " . date("Y-m-d H:i:s") . "\n");
fclose($handle);
}
?>
10. Working with Forms and HTTP
PHP excels at handling web forms and HTTP requests:
<?php
// HTML form (save as form.html)
/*
<form method="POST" action="process.php">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
*/
// Processing form data (process.php)
if ($_POST) {
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
// Validation
if (empty($username) || empty($email) || empty($password)) {
echo "All fields are required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Process the data
echo "Welcome, " . htmlspecialchars($username);
// Hash password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Save to database, etc.
}
}
// Working with GET parameters
$page = $_GET['page'] ?? 1;
$category = $_GET['category'] ?? 'all';
echo "Page: $page, Category: $category";
?>
11. Database Operations
PHP commonly works with databases, especially MySQL:
<?php
// Database connection using PDO
try {
$pdo = new PDO(
"mysql:host=localhost;dbname=mydb;charset=utf8",
"username",
"password",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// Prepared statements (secure)
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > ? AND city = ?");
$stmt->execute([18, "New York"]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "User: " . $row['name'] . "\n";
}
// Insert data
$stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
$stmt->execute(["John Doe", "[email protected]", 25]);
echo "Last inserted ID: " . $pdo->lastInsertId();
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>
12. Modern PHP Features (PHP 8.0+)
PHP 8.0+ introduced many modern features:
<?php
// Named arguments (PHP 8.0+)
function createUser($name, $email, $age = 18, $active = true) {
return compact('name', 'email', 'age', 'active');
}
$user = createUser(
name: "John",
email: "[email protected]",
active: false
);
// Match expression (PHP 8.0+)
$status_code = 200;
$message = match($status_code) {
200, 201 => 'Success',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown Status'
};
// Nullsafe operator (PHP 8.0+)
$user_name = $user?->profile?->name ?? 'Unknown';
// Constructor property promotion (PHP 8.0+)
class User {
public function __construct(
public string $name,
public string $email,
public int $age = 18,
private bool $active = true
) {}
public function isActive(): bool {
return $this->active;
}
}
$user = new User("John", "[email protected]", 25);
echo $user->name; // John
// Enums (PHP 8.1+)
enum Status {
case PENDING;
case APPROVED;
case REJECTED;
public function label(): string {
return match($this) {
Status::PENDING => 'Pending',
Status::APPROVED => 'Approved',
Status::REJECTED => 'Rejected',
};
}
}
$status = Status::PENDING;
echo $status->label(); // Pending
?>
13. Best Practices and Tips
Here are some essential PHP best practices:
<?php
// 1. Always use PHP opening tags
// Good: <?php
// Avoid: <? (short tags)
// 2. Use prepared statements for database queries
// Prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
// 3. Validate and sanitize input
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
// 4. Use meaningful variable names
// Good:
$user_age = 25;
$is_active = true;
// Bad:
$a = 25;
$flag = true;
// 5. Handle errors gracefully
function divide($a, $b) {
if ($b == 0) {
throw new InvalidArgumentException("Division by zero");
}
return $a / $b;
}
// 6. Use type declarations (PHP 7+)
function calculateTotal(array $items): float {
return array_sum($items);
}
// 7. Organize code with namespaces
namespace App\Models;
class User {
// class implementation
}
// 8. Use composer for dependency management
// composer.json example:
/*
{
"require": {
"monolog/monolog": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
*/
?>
PHP is a powerful and flexible language perfect for web development. This tutorial covered the essential concepts you need to start building PHP applications. Practice these concepts, explore PHP frameworks like Laravel or Symfony, and keep learning!