PHP Next Lesson: Working with Data - Arrays, Functions, and Forms
PHP Next Lesson: Working with Data - Arrays, Functions, and Forms
                                PHP Next Lesson: Working with Data - Arrays, Functions, and Forms
Welcome to your next PHP lesson! Now that you've built your first programs, let's dive deeper into essential PHP concepts that will make your applications more powerful and organized.
Lesson 2: Mastering Arrays, Functions, and Form Handling
Part 1: Deep Dive into Arrays
1.1 Different Types of Arrays
<?php
// Indexed arrays
$fruits = array("Apple", "Banana", "Orange");
$colors = ["Red", "Green", "Blue"];
// Associative arrays
$person = [
    "name" => "John Doe",
    "age" => 30,
    "city" => "New York"
];
// Multidimensional arrays
$employees = [
    ["name" => "Alice", "position" => "Developer", "salary" => 50000],
    ["name" => "Bob", "position" => "Designer", "salary" => 45000],
    ["name" => "Charlie", "position" => "Manager", "salary" => 60000]
];
?>
1.2 Array Operations - Practical Example
<!DOCTYPE html> <html> <head> <title>Array Operations</title> <style> .container { max-width: 800px; margin: 0 auto; padding: 20px; } .section { background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 5px; } </style> </head> <body> <div class="container"> <h1>PHP Array Operations</h1> <?php // Sample data $products = [ ["id" => 1, "name" => "Laptop", "price" => 999.99, "category" => "Electronics"], ["id" => 2, "name" => "Book", "price" => 19.99, "category" => "Education"], ["id" => 3, "name" => "Headphones", "price" => 149.99, "category" => "Electronics"], ["id" => 4, "name" => "Desk", "price" => 299.99, "category" => "Furniture"], ["id" => 5, "name" => "Pen", "price" => 2.99, "category" => "Office"] ]; // 1. Filter electronics products $electronics = array_filter($products, function($product) { return $product['category'] === 'Electronics'; }); // 2. Get only product names $productNames = array_column($products, 'name'); // 3. Calculate total value $totalValue = array_sum(array_column($products, 'price')); // 4. Sort by price (descending) $sortedProducts = $products; usort($sortedProducts, function($a, $b) { return $b['price'] <=> $a['price']; }); ?> <div class="section"> <h2>All Products</h2> <ul> <?php foreach($products as $product): ?> <li><?= $product['name'] ?> - $<?= $product['price'] ?> (<?= $product['category'] ?>)</li> <?php endforeach; ?> </ul> </div> <div class="section"> <h2>Electronics Only</h2> <ul> <?php foreach($electronics as $product): ?> <li><?= $product['name'] ?> - $<?= $product['price'] ?></li> <?php endforeach; ?> </ul> </div> <div class="section"> <h2>Statistics</h2> <p><strong>Total Inventory Value:</strong> $<?= number_format($totalValue, 2) ?></p> <p><strong>Number of Products:</strong> <?= count($products) ?></p> <p><strong>Average Price:</strong> $<?= number_format($totalValue / count($products), 2) ?></p> </div> <div class="section"> <h2>Products Sorted by Price (High to Low)</h2> <ul> <?php foreach($sortedProducts as $product): ?> <li><?= $product['name'] ?> - $<?= $product['price'] ?></li> <?php endforeach; ?> </ul> </div> </div> </body> </html>
Part 2: PHP Functions
2.1 Built-in PHP Functions
<?php
// String functions
$text = "Hello World!";
echo "Original: " . $text . "<br>";
echo "Length: " . strlen($text) . "<br>";
echo "Uppercase: " . strtoupper($text) . "<br>";
echo "Lowercase: " . strtolower($text) . "<br>";
echo "Word Count: " . str_word_count($text) . "<br>";
echo "Reversed: " . strrev($text) . "<br>";
// Date functions
echo "Today: " . date('Y-m-d') . "<br>";
echo "Current Time: " . date('H:i:s') . "<br>";
echo "Day of Week: " . date('l') . "<br>";
// Math functions
$number = 25.7;
echo "Number: $number<br>";
echo "Square Root: " . sqrt($number) . "<br>";
echo "Rounded: " . round($number) . "<br>";
echo "Absolute: " . abs(-$number) . "<br>";
?>
2.2 Creating Custom Functions
<?php
// Basic function
function greetUser($name, $timeOfDay = "day") {
    return "Good $timeOfDay, $name!";
}
// Function with return value
function calculateArea($length, $width = null) {
    if ($width === null) {
        // Square
        return $length * $length;
    } else {
        // Rectangle
        return $length * $width;
    }
}
// Function that modifies an array
function applyDiscount(&$products, $discountPercent) {
    foreach ($products as &$product) {
        $discount = $product['price'] * ($discountPercent / 100);
        $product['discounted_price'] = $product['price'] - $discount;
    }
    return $products;
}
// Using the functions
echo greetUser("John", "morning") . "<br>";
echo "Area of square (side 5): " . calculateArea(5) . "<br>";
echo "Area of rectangle (4x6): " . calculateArea(4, 6) . "<br>";
$sampleProducts = [
    ["name" => "Product A", "price" => 100],
    ["name" => "Product B", "price" => 200]
];
applyDiscount($sampleProducts, 10);
print_r($sampleProducts);
?>
Part 3: Advanced Form Handling with Validation
Let's build a complete user registration system:
<?php // Initialize variables $errors = []; $success = false; $formData = [ 'name' => '', 'email' => '', 'password' => '', 'age' => '', 'subscription' => 'basic' ]; // Form processing if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Sanitize input $formData['name'] = htmlspecialchars(trim($_POST['name'] ?? '')); $formData['email'] = htmlspecialchars(trim($_POST['email'] ?? '')); $formData['password'] = $_POST['password'] ?? ''; $formData['age'] = $_POST['age'] ?? ''; $formData['subscription'] = $_POST['subscription'] ?? 'basic'; $formData['interests'] = $_POST['interests'] ?? []; // Validation if (empty($formData['name'])) { $errors['name'] = "Name is required"; } elseif (strlen($formData['name']) < 2) { $errors['name'] = "Name must be at least 2 characters"; } if (empty($formData['email'])) { $errors['email'] = "Email is required"; } elseif (!filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) { $errors['email'] = "Invalid email format"; } if (empty($formData['password'])) { $errors['password'] = "Password is required"; } elseif (strlen($formData['password']) < 6) { $errors['password'] = "Password must be at least 6 characters"; } if (!empty($formData['age']) && ($formData['age'] < 13 || $formData['age'] > 120)) { $errors['age'] = "Age must be between 13 and 120"; } // If no errors, process the form if (empty($errors)) { $success = true; // In a real application, you would save to database here } } ?> <!DOCTYPE html> <html> <head> <title>User Registration Form</title> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; } input, select, textarea { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; } .error { color: red; font-size: 14px; margin-top: 5px; } .success { background: #d4edda; color: #155724; padding: 15px; border-radius: 4px; margin-bottom: 20px; } .checkbox-group { display: flex; flex-wrap: wrap; gap: 10px; } .checkbox-group label { font-weight: normal; } button { background: #007bff; color: white; padding: 12px 30px; border: none; border-radius: 4px; cursor: pointer; } button:hover { background: #0056b3; } </style> </head> <body> <h1>User Registration</h1> <?php if ($success): ?> <div class="success"> <h2>Registration Successful!</h2> <p>Thank you for registering, <?= $formData['name'] ?>!</p> <p><strong>Details:</strong></p> <ul> <li>Email: <?= $formData['email'] ?></li> <li>Subscription: <?= ucfirst($formData['subscription']) ?></li> <li>Interests: <?= !empty($formData['interests']) ? implode(', ', $formData['interests']) : 'None' ?></li> </ul> </div> <?php endif; ?> <form method="POST" action=""> <div class="form-group"> <label for="name">Full Name *</label> <input type="text" id="name" name="name" value="<?= $formData['name'] ?>" required> <?php if (isset($errors['name'])): ?> <div class="error"><?= $errors['name'] ?></div> <?php endif; ?> </div> <div class="form-group"> <label for="email">Email Address *</label> <input type="email" id="email" name="email" value="<?= $formData['email'] ?>" required> <?php if (isset($errors['email'])): ?> <div class="error"><?= $errors['email'] ?></div> <?php endif; ?> </div> <div class="form-group"> <label for="password">Password *</label> <input type="password" id="password" name="password" required> <?php if (isset($errors['password'])): ?> <div class="error"><?= $errors['password'] ?></div> <?php endif; ?> </div> <div class="form-group"> <label for="age">Age</label> <input type="number" id="age" name="age" value="<?= $formData['age'] ?>" min="13" max="120"> <?php if (isset($errors['age'])): ?> <div class="error"><?= $errors['age'] ?></div> <?php endif; ?> </div> <div class="form-group"> <label for="subscription">Subscription Type</label> <select id="subscription" name="subscription"> <option value="basic" <?= $formData['subscription'] === 'basic' ? 'selected' : '' ?>>Basic</option> <option value="premium" <?= $formData['subscription'] === 'premium' ? 'selected' : '' ?>>Premium</option> <option value="enterprise" <?= $formData['subscription'] === 'enterprise' ? 'selected' : '' ?>>Enterprise</option> </select> </div> <div class="form-group"> <label>Interests</label> <div class="checkbox-group"> <?php $interestOptions = ['Web Development', 'Data Science', 'Mobile Apps', 'AI/ML', 'Cloud Computing']; foreach ($interestOptions as $interest): ?> <label> <input type="checkbox" name="interests[]" value="<?= $interest ?>" <?= in_array($interest, $formData['interests']) ? 'checked' : '' ?>> <?= $interest ?> </label> <?php endforeach; ?> </div> </div> <button type="submit">Register</button> </form> </body> </html>
Part 4: Practical Project - Contact Management System
Let's build a complete contact management system that combines everything we've learned:
<?php session_start(); // Initialize contacts array if (!isset($_SESSION['contacts'])) { $_SESSION['contacts'] = []; } // Add new contact if (isset($_POST['add_contact'])) { $newContact = [ 'id' => uniqid(), 'name' => htmlspecialchars(trim($_POST['name'])), 'email' => htmlspecialchars(trim($_POST['email'])), 'phone' => htmlspecialchars(trim($_POST['phone'])), 'category' => $_POST['category'], 'created_at' => date('Y-m-d H:i:s') ]; $_SESSION['contacts'][] = $newContact; } // Delete contact if (isset($_GET['delete'])) { $contactId = $_GET['delete']; $_SESSION['contacts'] = array_filter($_SESSION['contacts'], function($contact) use ($contactId) { return $contact['id'] !== $contactId; }); header('Location: ' . str_replace('&delete=' . $contactId, '', $_SERVER['REQUEST_URI'])); exit; } // Search contacts $searchResults = $_SESSION['contacts']; if (isset($_GET['search']) && !empty($_GET['search'])) { $searchTerm = strtolower($_GET['search']); $searchResults = array_filter($_SESSION['contacts'], function($contact) use ($searchTerm) { return strpos(strtolower($contact['name']), $searchTerm) !== false || strpos(strtolower($contact['email']), $searchTerm) !== false; }); } // Get statistics function getContactStats($contacts) { $stats = [ 'total' => count($contacts), 'by_category' => array_count_values(array_column($contacts, 'category')), 'recent' => array_filter($contacts, function($contact) { return strtotime($contact['created_at']) > strtotime('-7 days'); }) ]; $stats['recent_count'] = count($stats['recent']); return $stats; } $stats = getContactStats($_SESSION['contacts']); ?> <!DOCTYPE html> <html> <head> <title>Contact Management System</title> <style> body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; } .container { display: grid; grid-template-columns: 1fr 2fr; gap: 20px; } .section { background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px; } .contact-form input, .contact-form select { width: 100%; padding: 10px; margin: 5px 0; border: 1px solid #ddd; border-radius: 4px; } .contact-item { background: white; padding: 15px; margin: 10px 0; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; } .stat-card { background: white; padding: 15px; text-align: center; border-radius: 5px; } .search-form { margin-bottom: 20px; } .category-personal { border-left: 4px solid #007bff; } .category-work { border-left: 4px solid #28a745; } .category-family { border-left: 4px solid #dc3545; } button { background: #007bff; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; } button:hover { background: #0056b3; } .delete-btn { background: #dc3545; } .delete-btn:hover { background: #c82333; } </style> </head> <body> <h1>Contact Management System</h1> <div class="container"> <!-- Left Column - Add Contact & Statistics --> <div> <div class="section"> <h2>Add New Contact</h2> <form method="POST" class="contact-form"> <input type="text" name="name" placeholder="Full Name" required> <input type="email" name="email" placeholder="Email Address" required> <input type="tel" name="phone" placeholder="Phone Number"> <select name="category" required> <option value="personal">Personal</option> <option value="work">Work</option> <option value="family">Family</option> </select> <button type="submit" name="add_contact">Add Contact</button> </form> </div> <div class="section"> <h2>Statistics</h2> <div class="stats-grid"> <div class="stat-card"> <h3><?= $stats['total'] ?></h3> <p>Total Contacts</p> </div> <div class="stat-card"> <h3><?= $stats['recent_count'] ?></h3> <p>Added This Week</p> </div> <div class="stat-card"> <h3><?= count($stats['by_category']) ?></h3> <p>Categories</p> </div> </div> <h3>Contacts by Category</h3> <?php foreach($stats['by_category'] as $category => $count): ?> <p><?= ucfirst($category) ?>: <?= $count ?> contacts</p> <?php endforeach; ?> </div> </div> <!-- Right Column - Contact List --> <div> <div class="section"> <h2>Contact List</h2> <form method="GET" class="search-form"> <input type="text" name="search" placeholder="Search contacts..." value="<?= $_GET['search'] ?? '' ?>"> <button type="submit">Search</button> <?php if (isset($_GET['search'])): ?> <a href="?">Clear Search</a> <?php endif; ?> </form> <?php if (empty($searchResults)): ?> <p>No contacts found.</p> <?php else: ?> <?php foreach($searchResults as $contact): ?> <div class="contact-item category-<?= $contact['category'] ?>"> <h3><?= $contact['name'] ?></h3> <p><strong>Email:</strong> <?= $contact['email'] ?></p> <p><strong>Phone:</strong> <?= $contact['phone'] ?: 'Not provided' ?></p> <p><strong>Category:</strong> <?= ucfirst($contact['category']) ?></p> <p><small>Added: <?= $contact['created_at'] ?></small></p> <a href="?delete=<?= $contact['id'] ?>" class="delete-btn" onclick="return confirm('Are you sure you want to delete this contact?')"> Delete </a> </div> <?php endforeach; ?> <?php endif; ?> </div> </div> </div> </body> </html>
Key Concepts Covered in This Lesson:
- 
Array Manipulation: Filtering, sorting, and transforming arrays
 - 
Custom Functions: Creating reusable code blocks
 - 
Form Validation: Client and server-side validation techniques
 - 
Session Management: Persisting data across page loads
 - 
Search Functionality: Implementing search features
 - 
Data Statistics: Calculating and displaying metrics
 
Practice Exercises:
- 
Modify the contact system to include email validation
 - 
Add functionality to edit existing contacts
 - 
Implement contact exporting to CSV format
 - 
Add pagination to handle large contact lists
 - 
Create a function to find duplicate contacts
 
Next Lesson Preview:
In Lesson 3, we'll cover:
- 
Working with databases (MySQL)
 - 
File handling and uploads
 - 
Object-Oriented PHP
 - 
Building a complete blog system
 
Great job completing this lesson! Practice these concepts by building your own variations of these projects.
What's Your Reaction?