PHP Master Guide - From Beginner to Expert

Complete PHP Master Guide - From Beginner to Expert

Complete PHP Master Guide

From absolute beginner to expert level - everything you need to know to master PHP programming in 2023

Published: June 15, 2023 Read time: 12 min Category: Web Development

Featured image: PHP code on a screen | Photo by Unsplash

PHP remains one of the most popular server-side scripting languages, powering over 78% of all websites with a known server-side programming language. Whether you're just starting or looking to level up your skills, this comprehensive guide will take you from PHP basics to advanced concepts.

Getting Started with PHP

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development but also used as a general-purpose programming language. It's open-source, cross-platform, and integrates seamlessly with HTML.

Basic PHP Syntax

PHP code is executed on the server, and the result is returned to the browser as plain HTML. PHP scripts start with <?php and end with ?>.

Basic PHP Syntax Example
<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multi-line comment block
that spans multiple lines
*/

echo "Hello, World!"; // Output: Hello, World!

// Variables start with a dollar sign
$variableName = "This is a variable";
$number = 42;
$floatNumber = 3.14;
$isTrue = true;

// Display variable value
echo $variableName;
?>

PHP Variables and Data Types

PHP is a loosely typed language, which means you don't have to declare the data type of a variable. PHP automatically converts the variable to the correct data type based on its value.

PHP Data Types and Variables
<?php
// String
$name = "John Doe";
echo "Name: " . $name . "<br>";

// Integer
$age = 30;
echo "Age: " . $age . "<br>";

// Float (floating point numbers)
$price = 19.99;
echo "Price: $" . $price . "<br>";

// Boolean
$isLoggedIn = true;
echo "Logged in: " . ($isLoggedIn ? "Yes" : "No") . "<br>";

// Array
$colors = array("Red", "Green", "Blue");
echo "First color: " . $colors[0] . "<br>";

// Object
class Car {
    public $model;
    public function __construct($model) {
        $this->model = $model;
    }
}
$myCar = new Car("Toyota");
echo "Car model: " . $myCar->model . "<br>";

// NULL
$nothing = null;
echo "Nothing: " . var_export($nothing, true) . "<br>";

// Resource (special variable holding a reference to external resource)
$file = fopen("example.txt", "r");
// ... use the file resource
fclose($file);
?>

Intermediate PHP Concepts

Conditional Statements and Loops

Control structures allow you to control the flow of your PHP code execution based on conditions or repeat operations.

Conditionals and Loops in PHP
<?php
// If statement
$temperature = 25;

if ($temperature > 30) {
    echo "It's hot outside!<br>";
} elseif ($temperature > 20) {
    echo "It's warm outside.<br>";
} else {
    echo "It's cool outside.<br>";
}

// Switch statement
$day = "Monday";

switch ($day) {
    case "Monday":
        echo "Start of the work week.<br>";
        break;
    case "Friday":
        echo "Last day of work week!<br>";
        break;
    default:
        echo "It's " . $day . ".<br>";
}

// For loop
echo "For loop: ";
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}
echo "<br>";

// While loop
echo "While loop: ";
$count = 1;
while ($count <= 3) {
    echo $count . " ";
    $count++;
}
echo "<br>";

// Foreach loop (for arrays)
$fruits = ["Apple", "Banana", "Cherry"];
echo "Fruits: ";
foreach ($fruits as $fruit) {
    echo $fruit . " ";
}
echo "<br>";

// Foreach with key-value pairs
$person = ["name" => "John", "age" => 30, "city" => "New York"];
foreach ($person as $key => $value) {
    echo ucfirst($key) . ": " . $value . "<br>";
}
?>

Functions in PHP

Functions are blocks of code that can be reused throughout your application. PHP has many built-in functions, and you can also create your own.

PHP Functions Example
<?php
// Basic function
function greet() {
    return "Hello, welcome to PHP!";
}
echo greet() . "<br>";

// Function with parameters
function add($a, $b) {
    return $a + $b;
}
echo "5 + 3 = " . add(5, 3) . "<br>";

// Function with default parameter value
function sayHello($name = "Guest") {
    return "Hello, " . $name . "!";
}
echo sayHello() . "<br>";
echo sayHello("Alice") . "<br>";

// Function with type declarations (PHP 7+)
function multiply(float $x, float $y): float {
    return $x * $y;
}
echo "2.5 * 4 = " . multiply(2.5, 4) . "<br>";

// Anonymous function (closure)
$multiplyByTwo = function($number) {
    return $number * 2;
};
echo "10 * 2 = " . $multiplyByTwo(10) . "<br>";

// Arrow function (PHP 7.4+)
$addFive = fn($x) => $x + 5;
echo "7 + 5 = " . $addFive(7) . "<br>";
?>

Advanced PHP Topics

Object-Oriented Programming (OOP)

PHP supports object-oriented programming, which allows you to create reusable code through classes and objects.

PHP OOP Example
<?php
// Define a class
class User {
    // Properties (attributes)
    private $username;
    private $email;
    public $role = "member";
    
    // Constructor method
    public function __construct($username, $email) {
        $this->username = $username;
        $this->email = $email;
        echo "User created: " . $username . "<br>";
    }
    
    // Methods (functions)
    public function getUsername() {
        return $this->username;
    }
    
    public function setEmail($email) {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->email = $email;
            return true;
        }
        return false;
    }
    
    public function getEmail() {
        return $this->email;
    }
    
    public function sendMessage($message) {
        return "Sending message to " . $this->username . ": " . $message;
    }
    
    // Destructor
    public function __destruct() {
        echo "User object destroyed for " . $this->username . "<br>";
    }
}

// Inheritance
class Admin extends User {
    public $role = "admin";
    public $permissions = ["create", "read", "update", "delete"];
    
    public function manageUsers() {
        return $this->getUsername() . " is managing users.";
    }
}

// Create objects (instances)
$user1 = new User("john_doe", "john@example.com");
$user2 = new User("jane_smith", "jane@example.com");

// Use object methods
echo $user1->sendMessage("Welcome to our site!") . "<br>";
echo "User email: " . $user1->getEmail() . "<br>";

// Create admin object
$admin = new Admin("admin_user", "admin@example.com");
echo $admin->manageUsers() . "<br>";
echo "Admin role: " . $admin->role . "<br>";

// Working with static properties and methods
class MathUtility {
    public static $pi = 3.14159;
    
    public static function square($number) {
        return $number * $number;
    }
}

echo "Pi value: " . MathUtility::$pi . "<br>";
echo "Square of 5: " . MathUtility::square(5) . "<br>";
?>

Working with Databases (MySQL)

PHP is often used with MySQL databases to create dynamic web applications. Here's an example using MySQLi (improved MySQL extension).

PHP with MySQL Database
<?php
// Database connection settings
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to the database<br>";

// Create a table (if not exists)
$sql = "CREATE TABLE IF NOT EXISTS users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {
    echo "Table 'users' created or already exists<br>";
} else {
    echo "Error creating table: " . $conn->error . "<br>";
}

// Insert data
$sql = "INSERT INTO users (firstname, lastname, email) 
        VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully<br>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error . "<br>";
}

// Query data
$sql = "SELECT id, firstname, lastname, email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<h3>User List:</h3>";
    echo "<ul>";
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<li>ID: " . $row["id"] . " - Name: " . 
             $row["firstname"] . " " . $row["lastname"] . 
             " - Email: " . $row["email"] . "</li>";
    }
    echo "</ul>";
} else {
    echo "0 results found<br>";
}

// Close connection
$conn->close();
?>

Conclusion

This guide has covered PHP from basic syntax to advanced OOP concepts and database integration. To truly master PHP, continue practicing by building projects, exploring popular frameworks like Laravel or Symfony, and staying updated with PHP 8+ features like attributes, match expressions, and nullsafe operator.

Remember that consistent practice is key to mastering any programming language. Start with simple scripts, gradually tackle more complex projects, and don't hesitate to explore the extensive PHP documentation and community resources available online.

Happy coding!