PHP Syntax and Basic Constructs
Learning Objectives
- Understand PHP basics
- Set up PHP development environment
- Write server-side code
- Prepare for WordPress development
Understanding PHP Syntax Fundamentals
Welcome to our exploration of PHP syntax and basic constructs! In this session, we'll dive into the foundational elements of PHP programming that form the building blocks for all PHP applications, including WordPress. By the end of this lecture, you'll understand how PHP code is structured, how to write basic PHP statements, and how the language's core constructs work together.
Think of PHP syntax as the grammar rules of a language. Just as natural languages have rules governing how words and sentences are formed, PHP has specific rules for how code must be written to be understood by the PHP interpreter. Mastering these rules is your first step toward becoming fluent in the PHP language.
PHP Variables: Storing and Manipulating Data
Variables are used to store data that can be referenced and manipulated throughout your code. In PHP, variables are denoted by a dollar sign ($) followed by the variable name.
Variable Naming Rules
- Must start with a letter or underscore (_)
- Can contain letters, numbers, and underscores
- Cannot contain spaces or special characters
- Are case-sensitive (
$nameand$Nameare different variables)
// Valid variable names
$name = "John";
$_age = 30;
$price1 = 19.99;
$user_email = "john@example.com";
// Invalid variable names
// $1price = 19.99; // Cannot start with a number
// $user-email = "john@example.com"; // Cannot contain hyphens
// $user name = "John"; // Cannot contain spaces
Variable Declaration and Assignment
In PHP, you don't need to declare a variable type before using it. PHP automatically converts the variable to the appropriate data type based on its context. This is known as "loose typing" or "dynamic typing."
// Variables are created the moment you assign a value
$name = "Alice"; // String
$age = 25; // Integer
$height = 5.8; // Float
$is_student = true; // Boolean
// Variables can change type when reassigned
$variable = "123"; // String
$variable = 123; // Now an Integer
$variable = true; // Now a Boolean
$variable = null; // Now Null
Think of PHP variables as labeled containers that can hold different types of content. The label (variable name) stays the same, but you can empty the container and put something completely different inside at any time. This flexibility is both a strength and a potential source of bugs if not managed carefully.
Variable Scope
The scope of a variable determines where in your code the variable can be accessed. PHP has several different variable scopes:
Local Scope
function testFunction() {
$localVar = "I'm local"; // Local to this function
echo $localVar; // Works fine
}
testFunction();
// echo $localVar; // Error: Undefined variable
Global Scope
$globalVar = "I'm global"; // Global scope
function testGlobal() {
global $globalVar; // Access global variable
echo $globalVar; // Works fine
// Alternative approach
echo $GLOBALS['globalVar']; // Also works
}
Static Variables
function counter() {
static $count = 0; // Initialized only once, retains value between calls
$count++;
echo $count;
}
counter(); // Outputs: 1
counter(); // Outputs: 2
counter(); // Outputs: 3
Best Practice: Limit the use of global variables as they can lead to unexpected side effects and make code harder to maintain. Instead, pass variables to functions as parameters and return values from functions.
PHP Data Types: Understanding What You're Working With
PHP supports several data types that determine what kind of data a variable can hold and what operations can be performed on it. Let's explore each type with examples and practical applications.
String
Strings are sequences of characters used to store text.
// String declaration
$single_quoted = 'This is a single-quoted string';
$double_quoted = "This is a double-quoted string";
// Differences between single and double quotes
$name = "Alice";
echo 'Hello, $name'; // Outputs: Hello, $name
echo "Hello, $name"; // Outputs: Hello, Alice
// String concatenation
$first_name = "John";
$last_name = "Doe";
$full_name = $first_name . " " . $last_name; // John Doe
// String functions
echo strlen($full_name); // 8 (length of string)
echo strtoupper($full_name); // JOHN DOE
echo strtolower($full_name); // john doe
echo str_replace("John", "Jane", $full_name); // Jane Doe
// Accessing characters
echo $full_name[0]; // J (first character)
echo $full_name[5]; // D (sixth character)
// Heredoc syntax (for longer strings)
$description = <<
Real-World Example: WordPress Post Content
// Retrieving and manipulating WordPress post content
$post_content = get_the_content();
// Strip all HTML tags for a plain text excerpt
$plain_text = strip_tags($post_content);
// Create an excerpt (first 150 characters)
$excerpt = substr($plain_text, 0, 150);
// Add ellipsis if the content was truncated
if (strlen($plain_text) > 150) {
$excerpt .= '...';
}
// Display the excerpt
echo $excerpt;
Integer
Integers are whole numbers without a decimal point.
// Integer declaration
$age = 25;
$temperature = -10;
$binary = 0b1010; // Binary (10 in decimal)
$octal = 0123; // Octal (83 in decimal)
$hex = 0x1A; // Hexadecimal (26 in decimal)
// Integer operations
$sum = 5 + 10; // 15
$difference = 20 - 5; // 15
$product = 4 * 5; // 20
$quotient = 20 / 4; // 5 (note: this actually returns a float in PHP)
$remainder = 15 % 4; // 3 (modulus/remainder)
$power = 2 ** 3; // 8 (exponentiation)
// Integer functions
echo is_int($age); // 1 (true)
echo max(1, 5, 3, 9); // 9
echo min(1, 5, 3, 9); // 1
echo abs(-10); // 10 (absolute value)
Real-World Example: WordPress Pagination
// WordPress pagination calculations
$posts_per_page = 10;
$total_posts = wp_count_posts()->publish;
$total_pages = ceil($total_posts / $posts_per_page);
// Get current page
$current_page = get_query_var('paged') ? get_query_var('paged') : 1;
// Calculate offset for query
$offset = ($current_page - 1) * $posts_per_page;
// Display pagination info
echo "Page $current_page of $total_pages";
Float
Floats (also called floating-point numbers or doubles) are numbers with a decimal point.
// Float declaration
$height = 5.9;
$pi = 3.14159;
$scientific = 1.5e3; // 1500 (scientific notation)
// Float operations (similar to integers)
$sum = 1.5 + 2.3; // 3.8
$product = 2.5 * 3; // 7.5
// Be careful with floating-point precision
echo 0.1 + 0.2; // Might display 0.30000000000000004
echo (0.1 + 0.2) == 0.3; // false (due to precision issues)
// Float functions
echo round(3.4); // 3
echo round(3.5); // 4
echo ceil(4.3); // 5 (round up)
echo floor(4.8); // 4 (round down)
echo number_format(1234.56, 1, '.', ','); // 1,234.6
Real-World Example: E-commerce Price Calculations
// WordPress WooCommerce price calculations
$product_price = 29.99;
$tax_rate = 0.07; // 7% tax
$shipping = 5.50;
// Calculate tax amount
$tax_amount = $product_price * $tax_rate;
// Calculate total
$total = $product_price + $tax_amount + $shipping;
// Format for display
echo "Product: $" . number_format($product_price, 2);
echo "Tax: $" . number_format($tax_amount, 2);
echo "Shipping: $" . number_format($shipping, 2);
echo "Total: $" . number_format($total, 2);
Boolean
Booleans represent truth values: true or false.
// Boolean declaration
$is_logged_in = true;
$is_admin = false;
// Logical operations
$and_result = true && false; // false
$or_result = true || false; // true
$not_result = !true; // false
// Comparison operations produce booleans
$comparison1 = (5 > 3); // true
$comparison2 = (10 == "10"); // true (loose comparison)
$comparison3 = (10 === "10"); // false (strict comparison)
// Truthy and falsy values
// The following values evaluate to false in a boolean context:
// false, 0, 0.0, "", "0", [], null, and unset variables
if (0) {
// This code will not execute
}
if ("hello") {
// This code will execute (non-empty strings are truthy)
}
Real-World Example: WordPress Conditional Display
// WordPress conditional content display
$is_user_logged_in = is_user_logged_in();
$is_admin = current_user_can('administrator');
$is_author = is_author();
// Display different content based on conditions
if ($is_user_logged_in && $is_admin) {
echo "Welcome, Administrator!";
} elseif ($is_user_logged_in) {
echo "Welcome back to our site!";
} else {
echo "Please log in to access all features.";
}
// Use in conditional statements for templates
if (has_post_thumbnail() && !is_single()) {
the_post_thumbnail('thumbnail');
}
Array
Arrays are ordered maps that can hold multiple values under a single variable name.
// Indexed array (numeric keys)
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // apple
echo $fruits[1]; // banana
// Associative array (string keys)
$person = [
"name" => "John",
"age" => 30,
"email" => "john@example.com"
];
echo $person["name"]; // John
echo $person["email"]; // john@example.com
// Multidimensional array
$users = [
["name" => "Alice", "role" => "Admin"],
["name" => "Bob", "role" => "Editor"],
["name" => "Charlie", "role" => "Subscriber"]
];
echo $users[1]["name"]; // Bob
echo $users[2]["role"]; // Subscriber
// Array functions
$numbers = [5, 3, 8, 1, 9];
sort($numbers); // Sorts array in ascending order
echo count($numbers); // 5 (number of elements)
echo in_array(8, $numbers); // true (checks if value exists in array)
echo array_sum($numbers); // 26 (sum of all values)
// Adding and removing elements
$colors = ["red", "green"];
$colors[] = "blue"; // Add to the end
array_push($colors, "yellow"); // Also adds to the end
array_unshift($colors, "purple"); // Add to the beginning
array_pop($colors); // Remove from the end
array_shift($colors); // Remove from the beginning
// Merging arrays
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2); // [1, 2, 3, 4, 5, 6]
// Iterate over an array
foreach ($fruits as $fruit) {
echo $fruit . " "; // apple banana cherry
}
// Iterate with keys
foreach ($person as $key => $value) {
echo "$key: $value
";
}
// Arrow function with array_map (PHP 7.4+)
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers); // [2, 4, 6, 8, 10]
Real-World Example: WordPress Navigation Menu
// WordPress menu configuration
$menu_items = wp_get_nav_menu_items('primary-menu');
// Process menu items
$processed_menu = [];
foreach ($menu_items as $item) {
$processed_menu[] = [
'id' => $item->ID,
'title' => $item->title,
'url' => $item->url,
'parent' => $item->menu_item_parent,
'classes' => implode(' ', $item->classes)
];
}
// Create hierarchical menu
$menu_hierarchy = [];
foreach ($processed_menu as $item) {
if ($item['parent'] == 0) {
$item['children'] = [];
$menu_hierarchy[$item['id']] = $item;
}
}
// Add child items
foreach ($processed_menu as $item) {
if ($item['parent'] != 0 && isset($menu_hierarchy[$item['parent']])) {
$menu_hierarchy[$item['parent']]['children'][] = $item;
}
}
// Display menu (simplified)
foreach ($menu_hierarchy as $item) {
echo '' . $item['title'] . '';
if (!empty($item['children'])) {
echo '';
foreach ($item['children'] as $child) {
echo '- ' . $child['title'] . '
';
}
echo '
';
}
echo ' ';
}
Null
Null represents a variable with no value. It's the only possible value of the null data type.
// Null assignment
$database_result = null;
// Check for null
if (is_null($database_result)) {
echo "No results found";
}
// Null coalescing operator (PHP 7+)
$username = $user_data['username'] ?? 'Guest'; // 'Guest' if username is null or doesn't exist
Real-World Example: WordPress Post Meta
// Handling WordPress post meta
$custom_field = get_post_meta($post_id, 'custom_field', true);
// If the meta doesn't exist or is empty, it might return an empty string or null
if (is_null($custom_field) || $custom_field === '') {
// Use default value
$custom_field = 'Default value';
}
// Alternative with null coalescing operator (PHP 7+)
$custom_field = get_post_meta($post_id, 'custom_field', true) ?? 'Default value';
Object
Objects are instances of classes that can contain properties and methods.
// Class definition
class Person {
// Properties
public $name;
public $age;
// Constructor
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// Method
public function greet() {
return "Hello, my name is {$this->name} and I am {$this->age} years old.";
}
}
// Creating an object
$person = new Person("Alice", 28);
// Accessing properties
echo $person->name; // Alice
echo $person->age; // 28
// Calling methods
echo $person->greet(); // Hello, my name is Alice and I am 28 years old.
Real-World Example: WordPress Custom Post Type
// Working with WordPress post objects
$post = get_post(123); // Returns a WP_Post object
// Accessing post properties
echo $post->ID; // Post ID
echo $post->post_title; // Post title
echo $post->post_content; // Post content
// Working with WordPress user objects
$current_user = wp_get_current_user();
if ($current_user->exists()) {
echo "Welcome, " . $current_user->display_name;
// Check user roles
if (in_array('administrator', $current_user->roles)) {
echo " (Administrator)";
}
}
PHP Operators: Performing Operations
Operators are symbols that tell the PHP interpreter to perform specific mathematical, relational, or logical operations. PHP offers a wide range of operators for different purposes.
Arithmetic Operators
Used for performing basic mathematical operations.
$a = 10;
$b = 3;
echo $a + $b; // 13 (Addition)
echo $a - $b; // 7 (Subtraction)
echo $a * $b; // 30 (Multiplication)
echo $a / $b; // 3.3333333333333 (Division)
echo $a % $b; // 1 (Modulus - remainder after division)
echo $a ** $b; // 1000 (Exponentiation - 10 to the power of 3)
Assignment Operators
Used to assign values to variables, often combined with arithmetic operations.
$a = 10; // Basic assignment
// Combined assignment operators
$a += 5; // Same as: $a = $a + 5; (now $a is 15)
$a -= 3; // Same as: $a = $a - 3; (now $a is 12)
$a *= 2; // Same as: $a = $a * 2; (now $a is 24)
$a /= 4; // Same as: $a = $a / 4; (now $a is 6)
$a %= 4; // Same as: $a = $a % 4; (now $a is 2)
$a **= 3; // Same as: $a = $a ** 3; (now $a is 8)
// String assignment operator
$str = "Hello";
$str .= " World"; // Same as: $str = $str . " World"; (now $str is "Hello World")
Comparison Operators
Used to compare two values in conditional expressions.
$a = 10;
$b = 5;
$c = "10";
// Equal
var_dump($a == $b); // bool(false) - values not equal
var_dump($a == $c); // bool(true) - values equal (loose comparison)
// Identical
var_dump($a === $c); // bool(false) - values equal but different types
// Not equal
var_dump($a != $b); // bool(true)
var_dump($a <> $b); // bool(true) (alternative)
// Not identical
var_dump($a !== $c); // bool(true)
// Greater than / less than
var_dump($a > $b); // bool(true)
var_dump($a < $b); // bool(false)
// Greater than or equal to / less than or equal to
var_dump($a >= $b); // bool(true)
var_dump($a <= $b); // bool(false)
// Spaceship operator (PHP 7+)
// Returns -1 if left is less, 0 if equal, 1 if greater
var_dump($a <=> $b); // int(1) (10 is greater than 5)
var_dump($b <=> $a); // int(-1) (5 is less than 10)
var_dump($a <=> 10); // int(0) (10 is equal to 10)
Best Practice: Use the identical operator (===) instead of the equal operator (==) when possible. The identical operator compares both value and type, which can prevent unexpected behavior.
Logical Operators
Used to combine conditional statements.
$a = true;
$b = false;
// AND
var_dump($a && $b); // bool(false)
var_dump($a and $b); // bool(false) (alternative syntax)
// OR
var_dump($a || $b); // bool(true)
var_dump($a or $b); // bool(true) (alternative syntax)
// XOR (exclusive OR - true if either is true, but not both)
var_dump($a xor $b); // bool(true)
// NOT
var_dump(!$a); // bool(false)
// Logical operators in conditional statements
$age = 25;
$has_membership = true;
if ($age >= 18 && $has_membership) {
echo "Access granted";
}
if ($age < 18 || !$has_membership) {
echo "Access denied";
}
Best Practice: Be aware of operator precedence. The && and || operators have higher precedence than the and and or operators. When in doubt, use parentheses to make your intention clear.
String Operators
Used to concatenate strings.
$first_name = "John";
$last_name = "Doe";
// Concatenation
$full_name = $first_name . " " . $last_name; // "John Doe"
// Concatenation assignment
$greeting = "Hello, ";
$greeting .= $full_name; // "Hello, John Doe"
Array Operators
Used to compare and manipulate arrays.
$array1 = ["a" => "apple", "b" => "banana"];
$array2 = ["c" => "cherry", "d" => "date"];
$array3 = ["a" => "pear", "e" => "elderberry"];
// Union
$union = $array1 + $array2;
// Result: ["a" => "apple", "b" => "banana", "c" => "cherry", "d" => "date"]
// Union with overlapping keys
$overlap = $array1 + $array3;
// Result: ["a" => "apple", "b" => "banana", "e" => "elderberry"]
// Note: $array1 values are kept for duplicate keys
// Equality (==)
var_dump($array1 == $array3); // bool(false) - different values
// Identity (===)
$array4 = ["a" => "apple", "b" => "banana"];
var_dump($array1 === $array4); // bool(true) - same keys, values, and order
Increment/Decrement Operators
Used to increase or decrease a variable's value by one.
$a = 5;
// Post-increment
$b = $a++; // $b gets 5, then $a becomes 6
// Pre-increment
$c = ++$a; // $a becomes 7, then $c gets 7
// Post-decrement
$d = $a--; // $d gets 7, then $a becomes 6
// Pre-decrement
$e = --$a; // $a becomes 5, then $e gets 5
Conditional (Ternary) Operator
A shorthand way to write if-else statements.
// Basic syntax: condition ? value_if_true : value_if_false
$age = 20;
$status = ($age >= 18) ? "adult" : "minor"; // "adult"
// Can be nested (but consider readability)
$age = 15;
$status = ($age >= 21) ? "adult (21+)" : (($age >= 18) ? "adult" : "minor"); // "minor"
// Shorthand ternary (PHP 5.3+)
// Returns the first operand if it evaluates to true, otherwise returns the second operand
$username = $_GET['username'] ?: "Guest"; // "Guest" if $_GET['username'] is falsy
Null Coalescing Operator
Returns the first operand if it exists and is not null, otherwise returns the second operand. (PHP 7+)
// Basic syntax: first_operand ?? second_operand
// Without null coalescing
$username = isset($_GET['username']) ? $_GET['username'] : "Guest";
// With null coalescing
$username = $_GET['username'] ?? "Guest";
// Can be chained
$username = $_GET['username'] ?? $_POST['username'] ?? $default_username ?? "Guest";
Real-World Example: WordPress Options
// Get WordPress option with fallback
$site_logo = get_option('site_logo') ?? get_theme_mod('logo') ?? get_template_directory_uri() . '/images/default-logo.png';
// Using with post meta
$custom_header = get_post_meta($post_id, 'custom_header', true) ?? 'Default Header';
// Form handling with multiple possible sources
$user_email = $_POST['email'] ?? $_GET['email'] ?? $current_user->user_email ?? '';
PHP Control Structures: Making Decisions and Loops
Control structures allow you to control the flow of your program's execution based on certain conditions or to repeat a block of code multiple times.
If, Elseif, Else
Used for conditional execution of code.
// Basic if statement
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
// If-else statement
$temperature = 15;
if ($temperature > 30) {
echo "It's hot outside!";
} else {
echo "It's not hot outside.";
}
// If-elseif-else statement
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} elseif ($score >= 60) {
echo "Grade: D";
} else {
echo "Grade: F";
}
// Nested if statements
$age = 25;
$has_license = true;
if ($age >= 18) {
if ($has_license) {
echo "You can drive.";
} else {
echo "You need a license to drive.";
}
} else {
echo "You are too young to drive.";
}
// Alternative syntax (useful in templates)
if ($is_admin): ?>
<div class="admin-panel">
Admin content here
</div>
<?php else: ?>
<div class="user-panel">
User content here
</div>
<?php endif; ?>
Real-World Example: WordPress Template Conditionals
// Conditional rendering in WordPress templates
if (is_single()): ?>
<h1><?php the_title(); ?></h1>
<div class="post-meta">
Posted on <?php the_date(); ?> by <?php the_author(); ?>
</div>
<div class="post-content">
<?php the_content(); ?>
</div>
<?php elseif (is_page()): ?>
<h1><?php the_title(); ?></h1>
<div class="page-content">
<?php the_content(); ?>
</div>
<?php elseif (is_archive()): ?>
<h1><?php the_archive_title(); ?></h1>
<div class="archive-description">
<?php the_archive_description(); ?>
</div>
<?php else: ?>
<h1>Blog</h1>
<div class="post-excerpt">
<?php the_excerpt(); ?>
</div>
<?php endif; ?>
Switch
Used as an alternative to multiple if-elseif statements when comparing the same variable against different values.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
echo "Middle of the work week";
break;
case "Friday":
echo "End of the work week";
break;
case "Saturday":
case "Sunday":
echo "Weekend";
break;
default:
echo "Invalid day";
}
// Note: The 'break' statement is important to prevent "fall-through"
// Without break, execution continues to the next case
// Alternative syntax (useful in templates)
switch ($user_role):
case 'administrator':
echo "Welcome, Administrator!";
break;
case 'editor':
echo "Welcome, Editor!";
break;
default:
echo "Welcome, User!";
endswitch;
Real-World Example: WordPress Content Types
// Handle different post formats in WordPress
$format = get_post_format() ?: 'standard';
switch ($format) {
case 'video':
// Display video player
$video_url = get_post_meta(get_the_ID(), 'video_url', true);
echo '';
echo wp_oembed_get($video_url);
echo '';
break;
case 'gallery':
// Display image gallery
$gallery_images = get_post_meta(get_the_ID(), 'gallery_images', true);
if (!empty($gallery_images)) {
echo '';
foreach ($gallery_images as $image_id) {
echo wp_get_attachment_image($image_id, 'medium');
}
echo '';
}
break;
case 'quote':
// Display quote
$quote = get_post_meta(get_the_ID(), 'quote_text', true);
$quote_author = get_post_meta(get_the_ID(), 'quote_author', true);
echo '';
echo $quote;
if (!empty($quote_author)) {
echo '' . $quote_author . '';
}
echo '
';
break;
default:
// Standard post format
the_content();
}
While Loop
Executes a block of code repeatedly as long as a specified condition is true.
// Basic while loop
$i = 1;
while ($i <= 5) {
echo "$i "; // Outputs: 1 2 3 4 5
$i++;
}
// While loop with break
$i = 1;
while (true) { // Infinite loop
echo "$i ";
$i++;
if ($i > 5) {
break; // Exit the loop
}
}
// While loop with continue
$i = 0;
while ($i < 10) {
$i++;
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo "$i "; // Outputs: 1 3 5 7 9
}
// Alternative syntax (useful in templates)
$posts = get_posts(['numberposts' => 5]);
$i = 0;
while ($i < count($posts)):
$post = $posts[$i];
setup_postdata($post);
?>
<h2><?php the_title(); ?></h2>
<div><?php the_excerpt(); ?></div>
<?php
$i++;
endwhile;
wp_reset_postdata();
Do-While Loop
Similar to a while loop, but ensures that the code block is executed at least once, even if the condition is false from the start.
// Basic do-while loop
$i = 1;
do {
echo "$i "; // Outputs: 1 2 3 4 5
$i++;
} while ($i <= 5);
// Do-while loop when condition is initially false
$i = 6;
do {
echo "$i "; // Still outputs: 6
$i++;
} while ($i <= 5); // Condition is false, but the loop ran once
// Do-while with break and continue
$i = 0;
do {
$i++;
if ($i == 3) {
continue; // Skip when $i is 3
}
if ($i > 5) {
break; // Exit the loop when $i is greater than 5
}
echo "$i "; // Outputs: 1 2 4 5
} while (true);
For Loop
A compact way to write loops with initial expression, condition, and increment expression in a single line.
// Basic for loop
for ($i = 1; $i <= 5; $i++) {
echo "$i "; // Outputs: 1 2 3 4 5
}
// Nested for loops (creating a simple multiplication table)
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "$i×$j=" . ($i * $j) . " ";
}
echo "
";
}
// Outputs:
// 1×1=1 1×2=2 1×3=3
// 2×1=2 2×2=4 2×3=6
// 3×1=3 3×2=6 3×3=9
// For loop with multiple expressions
for ($i = 1, $j = 10; $i <= 5; $i++, $j += 10) {
echo "$i:$j "; // Outputs: 1:10 2:20 3:30 4:40 5:50
}
// Alternative syntax (useful in templates)
$items = ['apple', 'banana', 'cherry'];
?>
<ul>
<?php for ($i = 0; $i < count($items); $i++): ?>
<li><?php echo $items[$i]; ?></li>
<?php endfor; ?>
</ul>
Real-World Example: WordPress Pagination
// Custom pagination display in WordPress
$current_page = get_query_var('paged') ? get_query_var('paged') : 1;
$total_pages = $wp_query->max_num_pages;
if ($total_pages > 1) {
echo '';
// Previous page
if ($current_page > 1) {
echo 'Previous';
}
// Page numbers
for ($i = 1; $i <= $total_pages; $i++) {
if ($i == $current_page) {
echo '' . $i . '';
} else {
echo '' . $i . '';
}
}
// Next page
if ($current_page < $total_pages) {
echo 'Next';
}
echo '';
}
Foreach Loop
Specifically designed for iterating over arrays and objects, making it very useful in PHP applications.
// Foreach with indexed array
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo "$fruit "; // Outputs: apple banana cherry
}
// Foreach with associative array - key and value
$person = [
"name" => "John",
"age" => 30,
"occupation" => "Developer"
];
foreach ($person as $key => $value) {
echo "$key: $value
";
}
// Outputs:
// name: John
// age: 30
// occupation: Developer
// Foreach with reference (&) to modify array values
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as &$number) {
$number *= 2; // Double each number
}
// $numbers is now [2, 4, 6, 8, 10]
// Alternative syntax (useful in templates)
$posts = get_posts(['numberposts' => 5]);
?>
<div class="posts">
<?php foreach ($posts as $post): setup_postdata($post); ?>
<article>
<h2><?php the_title(); ?></h2>
<div><?php the_excerpt(); ?></div>
</article>
<?php endforeach; wp_reset_postdata(); ?>
</div>
Real-World Example: WordPress Custom Fields
// Display custom fields in WordPress
$custom_fields = get_post_custom();
echo '';
echo 'Product Details
';
echo '';
foreach ($custom_fields as $key => $values) {
// Skip internal WordPress fields (prefixed with _)
if (substr($key, 0, 1) === '_') {
continue;
}
// Format the field name for display
$field_label = ucwords(str_replace('_', ' ', $key));
// Get the field value (could be multiple values)
$field_value = implode(', ', $values);
echo '- ' . $field_label . ': ' . $field_value . '
';
}
echo '
';
echo '';
Match Expression (PHP 8+)
A modern switch alternative that returns a value and uses strict comparison.
// Basic match expression
$status_code = 404;
$message = match ($status_code) {
200, 201 => "Success",
400 => "Bad request",
404 => "Not found",
500 => "Server error",
default => "Unknown status code"
};
echo $message; // Outputs: Not found
// Match with expressions
$age = 20;
$category = match (true) {
$age < 13 => "Child",
$age < 18 => "Teenager",
$age < 65 => "Adult",
default => "Senior"
};
echo $category; // Outputs: Adult
Best Practice: If you're using PHP 8+, consider using match expressions instead of switch statements for cleaner code and safer comparisons (match uses strict comparison and doesn't require break statements).
Including Files in PHP
PHP provides several statements for including external files in your scripts, which are essential for organizing code and promoting reusability.
Include, Require, Include_Once, and Require_Once
| Statement | Description | Behavior if File Not Found |
|---|---|---|
include |
Includes and evaluates the specified file | Warning, script continues |
require |
Includes and evaluates the specified file | Fatal error, script stops |
include_once |
Includes the file if it hasn't been included before | Warning, script continues |
require_once |
Includes the file if it hasn't been included before | Fatal error, script stops |
// Include a file (script continues even if file is not found)
include 'header.php';
// Require a file (script stops if file is not found)
require 'config.php';
// Include a file only once (avoids duplicate function definitions)
include_once 'functions.php';
// Require a file only once (avoids duplicate function definitions)
require_once 'database.php';
Best Practice:
- Use
requirefor critical files that must be present for your application to work. - Use
includefor non-critical files where the application can continue without them. - Use
require_oncefor files containing function definitions or class declarations to avoid redefinition errors. - Use relative paths with caution, as they're relative to the file in which the include is called, not the entry script.
Real-World Example: WordPress Theme Structure
WordPress themes extensively use file inclusion to organize their codebase. Here's a simplified example of how a WordPress theme might structure its files:
// index.php (Main template file)
// functions.php (Theme functions file)
Basic Error Handling in PHP
Error handling is a crucial aspect of PHP development. Understanding how to properly handle errors will help you build more robust applications.
Common PHP Error Types
- Parse Error / Syntax Error: Code cannot be parsed (e.g., missing semicolon)
- Fatal Error: Critical error that stops script execution (e.g., calling undefined function)
- Warning: Non-fatal error (e.g., including a file that doesn't exist)
- Notice: Minor issue, often related to variables (e.g., using an undefined variable)
- Strict: Suggestion for code improvement (e.g., deprecated functionality)
- Deprecated: Function or feature that will be removed in future PHP versions
Error Handling Techniques
Error Reporting Level
// Show all errors (during development)
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Hide all errors (in production)
error_reporting(0);
ini_set('display_errors', 0);
// Log errors instead of displaying them (recommended for production)
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');
Try-Catch Blocks
// Basic try-catch
try {
// Code that might throw an exception
$result = 10 / 0; // This will cause an error
} catch (Exception $e) {
// Handle the exception
echo "An error occurred: " . $e->getMessage();
}
// Try-catch with multiple catch blocks (PHP 7.1+)
try {
// Some risky code
if (!file_exists('config.php')) {
throw new Exception('Config file not found');
}
$config = json_decode(file_get_contents('config.php'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JsonException('Invalid JSON in config file');
}
} catch (JsonException $e) {
// Handle JSON-specific errors
error_log('JSON error: ' . $e->getMessage());
die('Configuration error. Please contact support.');
} catch (Exception $e) {
// Handle other exceptions
error_log('General error: ' . $e->getMessage());
die('An error occurred. Please try again later.');
}
// Try-catch-finally (PHP 5.5+)
try {
// Open a file
$file = fopen('data.txt', 'r');
// Process the file
$content = fread($file, filesize('data.txt'));
} catch (Exception $e) {
// Handle any errors
echo "Error: " . $e->getMessage();
} finally {
// This code always runs, whether an exception occurred or not
if (isset($file) && $file) {
fclose($file); // Ensure file is closed
}
}
Custom Error Handler
// Custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
// Log the error
error_log("Error [$errno]: $errstr in $errfile on line $errline");
// User-friendly message
echo "Sorry, an error occurred. Please try again later.";
// Don't execute PHP's internal error handler
return true;
}
// Set the custom error handler
set_error_handler("customErrorHandler");
// Now errors will be handled by your function
$undefined_variable = $non_existent; // This would trigger the custom handler
Error Handling in WordPress
WordPress provides its own functions for error handling and debugging:
// Enable WordPress debugging (in wp-config.php)
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true); // Log errors to wp-content/debug.log
define('WP_DEBUG_DISPLAY', false); // Don't display errors on the site
// Custom error handling for specific functions
function get_post_safe($post_id) {
$post = get_post($post_id);
if (null === $post) {
// Log the error
error_log("Attempted to get non-existent post with ID: $post_id");
// Return a fallback
return false;
}
return $post;
}
// Usage
$post = get_post_safe(123);
if (!$post) {
echo "Post not found.";
} else {
echo $post->post_title;
}
Error Handling Best Practices
- Never display sensitive error information to users in production
- Always log errors for debugging purposes
- Use try-catch blocks for code that might throw exceptions
- Validate input data before processing to prevent errors
- Provide user-friendly error messages
- Check return values from functions for error conditions
What's Next?
Now that you understand the fundamental syntax and constructs of PHP, we'll dive deeper in the upcoming sessions:
- Functions and function definitions
- Object-oriented programming in PHP
- Working with forms and user input
- File handling and uploading
- MySQL database operations
- Introduction to WordPress development
Homework Assignment
Create a PHP script that demonstrates your understanding of PHP syntax and basic constructs by building a simple "Product Information" page that:
- Defines an array of at least five products with properties (name, price, description, category, in_stock)
- Uses conditional statements to display products differently based on availability
- Uses a loop to iterate through the products and display them
- Includes a function to format prices with a currency symbol
- Uses proper PHP tags, comments, and error handling
Submit your PHP file to the course learning management system.
PHP Comments: Documenting Your Code
Comments are non-executable lines of code that serve as notes to yourself and other developers. They are ignored by the PHP interpreter and are essential for maintaining readable and understandable code.
Single-Line Comments
Multi-Line Comments
Best Practice: Comment your code effectively by:
DocBlock Comments
DocBlock comments are a special format used for documenting functions, classes, and methods. They're particularly important in WordPress development for maintaining code quality.