Skip to Content
Course content

8: Arrays and Array Functions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of an array like a physical organizer—maybe a spice rack or a tool chest. If you have a simple tray with five slots, you don't necessarily need to label each slot; you just know that the salt is in slot 0, the pepper is in slot 1, and the garlic powder is in slot 2. That's how a basic list works. But if you're dealing with a massive chest of tools, you aren't going to remember that the 142nd drawer contains the Phillips head screwdriver. Instead, you put a label on the drawer that says "Screwdrivers." Now, you don't care about the position; you just ask the chest for the "Screwdrivers" drawer.

In PHP, that first scenario is an Indexed Array (where the position is the key), and the second is an Associative Array (where you define your own string-based keys). I've found that most of your time in PHP will be spent moving data between these two formats, especially when dealing with databases.

Storing Simple Lists with Indexed Arrays

When you just need a collection of similar things, use an indexed array. You don't have to manually assign numbers; PHP handles the indexing for you, starting at zero. I'll be honest: starting at zero always trips up beginners, but you'll get used to it. It's the industry standard.

// A simple list of pending notifications for a user
$notifications = ["Your order has shipped", "New message from Sarah", "Password change alert"];

// Accessing the first item
echo $notifications[0]; // Outputs: Your order has shipped

// Adding a new item to the end
$notifications[] = "Your subscription expires in 3 days";

Giving Your Data a Name with Associative Arrays

Indexed arrays are great until you need to represent a real "object," like a user profile or a product. You wouldn't want to remember that index 3 is the user's email and index 7 is their zip code. That's a recipe for a bug that's a nightmare to debug. Use associative arrays instead.

$user_profile = [
    "username" => "coder_jane",
    "email" => "jane@example.com",
    "role" => "administrator",
    "join_date" => "2023-11-12"
];

// No more guessing numbers. Just use the key.
echo "Welcome back, " . $user_profile['username'];

Cleaning Up and Manipulating Your Lists

PHP has a massive library of built-in array functions. You don't need to memorize all of them—even I still check the manual—but there are a few you'll use daily. For example, if you need to check if a specific value exists in a list, don't write a manual loop. Use in_array().

$banned_users = ["bad_actor1", "spammer_99", "troll_face"];
$current_user = "spammer_99";

if (in_array($current_user, $banned_users)) {
    die("You are not allowed to access this page.");
}

Then there's the power of array_merge(). I use this constantly when I'm combining default configuration settings with user-defined overrides. It takes two or more arrays and mashes them into one.

$defaults = ["theme" => "light", "notifications" => true, "timezone" => "UTC"];
$user_settings = ["theme" => "dark"];

// This keeps the defaults but lets the user settings overwrite specific keys
$final_config = array_merge($defaults, $user_settings);
// $final_config is now: ["theme" => "dark", "notifications" => true, "timezone" => "UTC"]

One last tip: if you ever need to quickly see what's actually inside an array while you're coding, avoid using echo. You can't echo an array. Use print_r() or var_dump() wrapped in <pre> tags to make it readable in the browser.

echo "<pre>";
print_r($final_config);
echo "</pre>";



📋 Practical Task

Build a Simple Movie Rating System

Your goal is to create a script that manages a small library of movies and their ratings. Follow these requirements:

  • Create an associative array called $movies where the keys are movie titles and the values are their ratings (1-10). Include at least four movies.
  • Add a new movie to the array using the associative syntax.
  • Create a second array called $watchlist containing three movie titles as a simple indexed list.
  • Write a piece of logic that checks if the first movie in your $watchlist exists in your $movies array.
  • If it exists, print the movie title and its rating. If it doesn't, print a message saying "Rating not yet available for this movie."
Rating
0 0

There are no comments for now.

to be the first to leave a comment.