Introduction
Welcome to Module 2: PHP Basics of our Master PHP from Basics to Advanced series! In this module, we’ll build on the foundations from Module 1, diving deep into the core building blocks of PHP programming: variables, constants, data types, type casting, type juggling, operators, strings, and cutting-edge PHP 8 features like union types and match expressions. Whether you’re a beginner creating your first dynamic website or an advanced developer exploring modern PHP, this guide is designed to be engaging, practical, and comprehensive.PHP is a cornerstone of web development, powering over 78% of websites (as of 2025), including platforms like WordPress and Laravel-based applications. This module equips you with the skills to manipulate data, perform calculations, and handle strings effectively, all while adhering to best practices. With real-life examples, pros, cons, alternatives, and SEO-friendly content, let’s make PHP exciting and accessible!
Module 2: PHP Basics1. Variables & ConstantsVariablesVariables in PHP store data and are declared with a $ symbol followed by a name. They’re case-sensitive and don’t require explicit type declaration due to PHP’s loose typing.Syntax:Rules:ConstantsConstants are immutable values defined using define() or the const keyword. They’re typically uppercase and global in scope.Syntax:Example:Real-Life Example: An e-commerce site uses constants for fixed values like tax rates or discount percentages to ensure consistency across calculations.Pros:
2. Data Types (int, float, string, bool, arrays, objects)PHP supports multiple data types, and its dynamic typing allows variables to change types based on context.IntegerWhole numbers (e.g., 42, -10).Example:FloatDecimal numbers (e.g., 3.14, -0.001).Example:StringText enclosed in single (') or double (") quotes.Example:Booleantrue or false.Example:ArrayA collection of values, indexed or associative.Example:ObjectInstances of classes, used for object-oriented programming.Example:Real-Life Example: A blog platform stores posts in an array and uses objects to manage user profiles:Pros:
3. Type Casting & Type JugglingType JugglingPHP automatically converts types during operations (e.g., "5" + 5 = 10).Example:Type CastingExplicitly convert types using (type) or functions like intval().Example:Real-Life Example: A form submission converts user input (string) to a number for calculations:Pros:
4. Operators (Arithmetic, Assignment, Comparison, Logical)Arithmetic Operators+, -, *, /, %, ** (exponentiation).Example:Assignment Operators=, +=, -=, *=, etc.Example:Comparison Operators==, ===, !=, !==, <, >, <=, >=, <=> (spaceship).Example:Logical Operators&&, ||, !, and, or, xor.Example:Real-Life Example: A shopping cart calculates discounts based on conditions:Pros:
5. Strings & String FunctionsString BasicsStrings are sequences of characters, created with single or double quotes.Example:Common String FunctionsReal-Life Example: A blog platform sanitizes and formats user comments:Pros:
6. PHP 8: Union Types, Match ExpressionsUnion TypesIntroduced in PHP 8, union types allow a variable to accept multiple types.Example:Match ExpressionsA more concise alternative to switch, introduced in PHP 8.Example:Real-Life Example: A user role system uses match expressions for clarity:Pros:
Advanced Scenarios
ConclusionYou’ve mastered Module 2: PHP Basics! From variables and constants to data types, operators, strings, and PHP 8 features, you’re now equipped to handle dynamic data and build interactive web applications. The real-life examples, such as form processing and e-commerce calculations, show how PHP powers modern websites. With best practices like strict typing and secure string handling, you’re ready to write clean, efficient code.
Module 2: PHP Basics1. Variables & ConstantsVariablesVariables in PHP store data and are declared with a $ symbol followed by a name. They’re case-sensitive and don’t require explicit type declaration due to PHP’s loose typing.Syntax:
php
$name = "Alice"; // String
$age = 25; // Integer
- Start with $, followed by a letter or underscore.
- No spaces or special characters (except underscore).
- Case-sensitive: $name ≠ $Name.
php
<?php
$username = "john_doe";
$email = "john@example.com";
$isActive = true;
echo "User: $username, Email: $email, Active: " . ($isActive ? "Yes" : "No");
?>
php
define("SITE_NAME", "MyBlog");
const MAX_USERS = 100;
php
<?php
define("TAX_RATE", 0.15);
$price = 100;
$tax = $price * TAX_RATE;
echo "Total with tax: $" . ($price + $tax); // Output: Total with tax: $115
?>
- Variables are flexible and easy to use.
- Constants prevent accidental changes to critical values.
- Loose typing can lead to errors (e.g., $price = "100" + 5).
- Constants are less flexible for dynamic data.
- Use meaningful variable names (e.g., $userAge instead of $a).
- Define constants for fixed values like API keys or site settings.
- Use const for class constants and define() for global constants.
2. Data Types (int, float, string, bool, arrays, objects)PHP supports multiple data types, and its dynamic typing allows variables to change types based on context.IntegerWhole numbers (e.g., 42, -10).Example:
php
$quantity = 5;
$stock = -2;
echo $quantity + $stock; // Output: 3
php
$price = 19.99;
$discount = 0.1;
echo $price * (1 - $discount); // Output: 17.991
php
$name = "Alice";
$greeting = "Hello, $name!"; // Double quotes allow variable interpolation
echo $greeting; // Output: Hello, Alice!
php
$isLoggedIn = true;
if ($isLoggedIn) {
echo "Welcome back!";
}
php
$fruits = ["apple", "banana", "orange"];
$user = ["name" => "John", "age" => 30];
echo $fruits[0]; // Output: apple
echo $user["name"]; // Output: John
php
class User {
public $name;
public function greet() {
return "Hello, " . $this->name . "!";
}
}
$user = new User();
$user->name = "Emma";
echo $user->greet(); // Output: Hello, Emma!
php
$posts = [
["title" => "PHP Basics", "author" => "John"],
["title" => "Advanced PHP", "author" => "Emma"]
];
foreach ($posts as $post) {
echo "{$post['title']} by {$post['author']}<br>";
}
- Flexible data types for rapid development.
- Arrays are versatile for lists and key-value pairs.
- Objects support complex OOP patterns.
- Loose typing can cause unexpected behavior.
- Arrays can become memory-intensive for large datasets.
- Use specific data types when possible (e.g., int for IDs).
- Validate array inputs to prevent undefined index errors.
- Use objects for structured, reusable code.
3. Type Casting & Type JugglingType JugglingPHP automatically converts types during operations (e.g., "5" + 5 = 10).Example:
php
$stringNum = "10";
$result = $stringNum + 5; // PHP converts "10" to int
echo $result; // Output: 15
php
$string = "42.75";
$int = (int)$string; // Cast to integer
$float = (float)$string; // Cast to float
echo $int; // Output: 42
echo $float; // Output: 42.75
php
<?php
$inputPrice = $_POST['price']; // "99.99"
$price = (float)$inputPrice;
$tax = $price * 0.1;
echo "Total: $" . ($price + $tax); // Output: Total: $109.989
?>
- Type juggling simplifies coding.
- Type casting ensures predictable results.
- Type juggling can lead to bugs (e.g., "10abc" + 5 = 15).
- Explicit casting adds verbosity.
- Use declare(strict_types=1); for strict typing.
- Validate inputs before casting.
- Use is_int(), is_float(), etc., to check types.
4. Operators (Arithmetic, Assignment, Comparison, Logical)Arithmetic Operators+, -, *, /, %, ** (exponentiation).Example:
php
$a = 10;
$b = 3;
echo $a + $b; // 13
echo $a % $b; // 1
echo $a ** 2; // 100
php
$total = 100;
$total += 50; // $total = $total + 50
echo $total; // 150
php
$a = "5";
$b = 5;
echo $a == $b ? "Equal" : "Not equal"; // Equal
echo $a === $b ? "Identical" : "Not identical"; // Not identical
php
$age = 25;
$isStudent = true;
if ($age >= 18 && $isStudent) {
echo "Eligible for discount";
}
php
<?php
$cartTotal = 200;
$isMember = true;
$hasCoupon = false;
$discount = ($cartTotal > 100 && $isMember) || $hasCoupon ? 20 : 0;
echo "Discount: $$discount"; // Output: Discount: $20
?>
- Operators enable complex logic and calculations.
- Spaceship operator simplifies comparisons.
- Loose comparison (==) can cause errors.
- Operator precedence can be confusing.
- Use === for strict comparisons.
- Parenthesize complex expressions for clarity.
- Avoid nested ternary operators.
5. Strings & String FunctionsString BasicsStrings are sequences of characters, created with single or double quotes.Example:
php
$single = 'Hello';
$double = "World";
echo "$single $double!"; // Output: Hello World!
- strlen(): Get string length.
- strtoupper(), strtolower(): Convert case.
- trim(): Remove whitespace.
- str_replace(): Replace substrings.
- substr(): Extract a portion.
- explode(): Split string into array.
- implode(): Join array into string.
php
$text = " Hello, PHP! ";
echo strlen($text); // 15
echo trim($text); // Hello, PHP!
echo strtoupper($text); // HELLO, PHP!
echo str_replace("PHP", "World", $text); // Hello, World!
$words = explode(",", $text); // [" Hello", " PHP! "]
echo implode(" ", $words); // Hello PHP!
php
<?php
$comment = " Great post!!! ";
$cleanComment = trim($comment);
$formattedComment = str_replace("!!!", "!", $cleanComment);
echo htmlspecialchars($formattedComment); // Output: Great post!
?>
- Rich string functions simplify text processing.
- Easy to manipulate user input.
- Inconsistent function naming (e.g., strtolower vs. str_replace).
- Large strings can be memory-intensive.
- Use htmlspecialchars() for output to prevent XSS.
- Validate string inputs to avoid errors.
- Use multibyte functions (e.g., mb_strlen) for Unicode support.
6. PHP 8: Union Types, Match ExpressionsUnion TypesIntroduced in PHP 8, union types allow a variable to accept multiple types.Example:
php
function processInput(int|float $number): string {
return "Processed: $number";
}
echo processInput(42); // Processed: 42
echo processInput(3.14); // Processed: 3.14
php
$status = 1;
$result = match ($status) {
1 => "Active",
2 => "Inactive",
default => "Unknown",
};
echo $result; // Output: Active
php
<?php
$role = "admin";
$permissions = match ($role) {
"admin" => ["edit", "delete", "view"],
"editor" => ["edit", "view"],
"viewer" => ["view"],
default => [],
};
print_r($permissions); // Output: Array ( [0] => edit [1] => delete [2] => view )
?>
- Union types improve type safety.
- Match expressions are concise and readable.
- Union types add complexity for beginners.
- Match expressions don’t support fall-through like switch.
- Use union types sparingly to avoid overcomplication.
- Combine match expressions with strict typing.
- Test PHP 8 features in a modern environment (PHP 8.2+).
Advanced Scenarios
- Dynamic Form Processing: Validate and process form inputs using type casting and operators:php
<?php $input = $_POST['age'] ?? "0"; $age = (int)$input; $message = $age >= 18 ? "Adult" : "Minor"; echo $message; ?>
- E-Commerce Calculator: Calculate order totals with taxes and discounts:php
<?php define("TAX_RATE", 0.08); $items = ["book" => 20.00, "pen" => 2.50]; $total = array_sum($items); $tax = $total * TAX_RATE; echo "Total: $" . number_format($total + $tax, 2); ?>
- User Profile System: Use objects and arrays to manage user data:php
<?php class UserProfile { public string $name; public array $preferences; public function __construct(string $name, array $preferences) { $this->name = $name; $this->preferences = $preferences; } public function display(): string { return "User: $this->name, Likes: " . implode(", ", $this->preferences); } } $user = new UserProfile("Alice", ["coding", "reading"]); echo $user->display(); ?>
ConclusionYou’ve mastered Module 2: PHP Basics! From variables and constants to data types, operators, strings, and PHP 8 features, you’re now equipped to handle dynamic data and build interactive web applications. The real-life examples, such as form processing and e-commerce calculations, show how PHP powers modern websites. With best practices like strict typing and secure string handling, you’re ready to write clean, efficient code.
0 comments:
Post a Comment