Lesson 3.1: Arrays and Array Functions

Arrays are like digital toolboxes—they organize multiple pieces of related information in one convenient container. Imagine trying to manage a grocery list by creating separate variables like $item1, $item2, $item3 for every single thing you need to buy. You'd end up with hundreds of variables! Arrays solve this problem by letting you store entire collections of data under one name.

Think about your smartphone's contact list. Instead of remembering every phone number separately, your phone organizes all contacts in one place where you can search, sort, and manage them easily. Arrays work exactly the same way in programming—they're your data organization superpower.

Why Arrays Matter in Real Applications

Before diving into code, let's understand why arrays are everywhere in web development:

Without arrays, these applications would be virtually impossible to build efficiently.

Your First Real Array

Let's start with something practical—managing a simple product inventory:

<?php
// Creating a product list the easy way
$products = ["Laptop", "Mouse", "Keyboard", "Monitor"];

// Adding a new product
$products[] = "Webcam";

// Checking what we have
echo "We have " . count($products) . " products in stock\n";
echo "First product: " . $products[0] . "\n";
echo "Latest addition: " . $products[4] . "\n";
?>

Notice how we use square brackets [] to add items and numbers starting from 0 to access them. This is called an "indexed array" because each item gets an automatic number (index).

Beyond Simple Lists: Associative Arrays

Indexed arrays work great for simple lists, but what if you need to store more complex information? That's where associative arrays shine—they let you use descriptive names instead of numbers:

<?php
// Storing detailed product information
$laptop = [
    "name" => "Gaming Laptop",
    "price" => 899.99,
    "brand" => "TechCorp",
    "in_stock" => true,
    "quantity" => 5
];

// Much more readable than $laptop[0], $laptop[1], etc!
echo "Product: " . $laptop["name"] . "\n";
echo "Price: $" . $laptop["price"] . "\n";
echo "Available: " . ($laptop["in_stock"] ? "Yes" : "No") . "\n";
?>

The arrow syntax => connects each key (like "name") to its value (like "Gaming Laptop"). This makes your code self-documenting—anyone reading it immediately understands what each piece of data represents.

Arrays Inside Arrays: Going Deeper

Real applications often need to store collections of complex items. Here's where multidimensional arrays become powerful:

<?php
// A catalog of multiple products
$inventory = [
    [
        "name" => "Laptop",
        "price" => 899.99,
        "category" => "Electronics"
    ],
    [
        "name" => "Coffee Mug",
        "price" => 12.99,
        "category" => "Kitchen"
    ],
    [
        "name" => "Desk Chair",
        "price" => 199.99,
        "category" => "Furniture"
    ]
];

// Accessing nested data
echo "First product: " . $inventory[0]["name"] . "\n";
echo "Second product price: $" . $inventory[1]["price"] . "\n";
?>

Think of this like a filing cabinet with multiple drawers (the outer array), where each drawer contains folders (the inner arrays) with detailed information.

Essential Array Tools: The Functions You'll Use Daily

PHP provides dozens of built-in functions to work with arrays. Let's explore the ones you'll use most often.

Adding and Removing Items

Managing array contents is fundamental to most applications:

<?php
$shoppingCart = ["laptop", "mouse"];

// Adding items
array_push($shoppingCart, "keyboard", "monitor");
echo "Cart contents: " . implode(", ", $shoppingCart) . "\n";

// Removing the last item
$removedItem = array_pop($shoppingCart);
echo "Removed: $removedItem\n";
echo "Cart now: " . implode(", ", $shoppingCart) . "\n";
?>

The implode() function is incredibly useful—it joins array elements into a single string with whatever separator you choose.

Finding What You Need

Searching through arrays is something you'll do constantly:

<?php
$availableColors = ["red", "blue", "green", "yellow", "purple"];

// Check if a color exists
if (in_array("blue", $availableColors)) {
    echo "Blue is available!\n";
}

// Find where something is located
$position = array_search("green", $availableColors);
echo "Green is at position: $position\n";
?>

Remember that array_search() returns false if it doesn't find anything, so always check your results carefully!

Organizing Your Data

Sorting makes information useful. Imagine trying to find a contact in an unsorted phone list:

<?php
$studentGrades = [
    "Alice" => 92,
    "Bob" => 87,
    "Charlie" => 94,
    "Diana" => 89
];

// Sort by grade (keeps names with grades)
asort($studentGrades);

echo "Students by grade (low to high):\n";
foreach ($studentGrades as $student => $grade) {
    echo "$student: $grade%\n";
}
?>

The asort() function sorts by values while keeping the key-value relationships intact—perfect for maintaining the connection between student names and their grades.

Real-World Example: Building a Simple User System

Let's combine what we've learned to solve a practical problem—managing user accounts:

<?php
// Our user database (in a real app, this would come from a database)
$users = [
    ["name" => "Alice Johnson", "email" => "[email protected]", "role" => "admin"],
    ["name" => "Bob Smith", "email" => "[email protected]", "role" => "user"],
    ["name" => "Charlie Brown", "email" => "[email protected]", "role" => "user"]
];

// Function to find admin users
function getAdmins($userList) {
    $admins = [];
    foreach ($userList as $user) {
        if ($user["role"] === "admin") {
            $admins[] = $user;
        }
    }
    return $admins;
}

// Function to get just the names
function getUserNames($userList) {
    $names = [];
    foreach ($userList as $user) {
        $names[] = $user["name"];
    }
    return $names;
}

// Using our functions
$adminUsers = getAdmins($users);
echo "Admin users: " . count($adminUsers) . "\n";

$allNames = getUserNames($users);
sort($allNames); // Alphabetical order
echo "All users: " . implode(", ", $allNames) . "\n";
?>

This example shows how arrays and functions work together to create useful, reusable code. The functions hide the complexity of searching and processing, giving you clean, easy-to-understand operations.

Power Tools: Advanced Array Functions

Once you're comfortable with basics, these advanced functions will supercharge your array operations.

Transforming Data with array_map()

Sometimes you need to modify every item in an array:

<?php
$prices = [10.00, 25.50, 15.75, 30.00];

// Add 20% tax to all prices
$pricesWithTax = array_map(function($price) {
    return $price * 1.20;
}, $prices);

echo "Original prices: " . implode(", ", $prices) . "\n";
echo "With tax: " . implode(", ", $pricesWithTax) . "\n";
?>

The array_map() function applies the same operation to every element, returning a new array with the results.

Filtering Data with array_filter()

Often you need to find items that meet specific criteria:

<?php
$products = [
    ["name" => "Laptop", "price" => 899],
    ["name" => "Mouse", "price" => 25],
    ["name" => "Monitor", "price" => 299],
    ["name" => "Keyboard", "price" => 75]
];

// Find expensive products (over $100)
$expensiveItems = array_filter($products, function($product) {
    return $product["price"] > 100;
});

echo "Expensive products:\n";
foreach ($expensiveItems as $product) {
    echo "- " . $product["name"] . " ($" . $product["price"] . ")\n";
}
?>

The array_filter() function keeps only the elements that make your test function return true.

Common Pitfalls and How to Avoid Them

Every developer makes these mistakes when learning arrays. Here's how to avoid them:

Mistake 1: Forgetting Array Indexes Start at 0

<?php
$fruits = ["apple", "banana", "cherry"];

// Wrong assumption
echo "First fruit: " . $fruits[1] . "\n"; // This gives you "banana"!

// Correct approach
echo "First fruit: " . $fruits[0] . "\n"; // This gives you "apple"
?>

Mistake 2: Not Checking if Keys Exist

<?php
$user = ["name" => "John", "email" => "[email protected]"];

// Dangerous - causes errors if key doesn't exist
// echo $user["phone"];

// Safe approach
if (isset($user["phone"])) {
    echo "Phone: " . $user["phone"] . "\n";
} else {
    echo "Phone number not provided\n";
}

// Even better (PHP 7+)
echo "Phone: " . ($user["phone"] ?? "Not provided") . "\n";
?>

The ?? operator is called the "null coalescing operator"—it gives you the value if it exists, or a default if it doesn't.

Performance Tips for Real Applications

As your applications grow, these tips will keep your arrays running smoothly:

Use Array Keys for Fast Lookups

<?php
// Slow for large arrays
$userIds = [1001, 1002, 1003, 1004, 1005];
$found = in_array(1004, $userIds); // Has to check each element

// Fast for any size
$userLookup = [1001 => true, 1002 => true, 1003 => true, 1004 => true, 1005 => true];
$found = isset($userLookup[1004]); // Instant lookup
?>

Choose the Right Tool for the Job

<?php
$numbers = [1, 2, 3, 4, 5];

// Good: Using built-in function
$sum = array_sum($numbers);

// Unnecessary: Manual loop for simple operations
$manualSum = 0;
foreach ($numbers as $number) {
    $manualSum += $number;
}

echo "Efficient sum: $sum\n";
?>

Built-in functions are usually optimized and tested extensively, so use them when they fit your needs.

Putting It All Together

Arrays are fundamental to virtually every web application you'll build. They store your data, organize your information, and provide the structure that makes complex applications possible.

Start with simple indexed arrays for lists, move to associative arrays when you need descriptive keys, and use multidimensional arrays for complex data structures. Master the essential functions like count(), in_array(), array_search(), and implode() first, then gradually incorporate more advanced tools like array_map() and array_filter().

Most importantly, remember that arrays are tools for solving real problems. Every time you work with collections of data—whether it's user accounts, product catalogs, form submissions, or search results—you'll reach for arrays to organize and manipulate that information effectively.

In the next lesson, we'll explore string manipulation, which often works hand-in-hand with arrays to process and format the textual data that users see in your applications.