Back to Blog
Lesson 7 of the PHP: Modern PHP from the Ground Up course
PHPJuly 25, 20264 min read

Introduction to PHP Arrays: Indexed and Associative Collections

Master PHP arrays to store and manage collections of data. Learn to create indexed and associative arrays for flexible, efficient backend development.

PHParraysweb developmentprogrammingassociative arraysdata structures
Close-up of PHP code on a monitor, highlighting development and programming concepts.

Previously in this course, we covered PHP variables and data types to store individual pieces of information. While single variables are essential, real-world applications rarely deal with just one value at a time; you’ll constantly need to group related data, such as a list of user IDs or a profile containing a name, email, and age. This lesson introduces PHP arrays, the primary data structure for handling these collections.

Understanding PHP Arrays

An array in PHP is an ordered map—a type that maps values to keys. Think of it as a container that holds multiple items under a single variable name. Unlike some languages where arrays are strictly lists of numbers, PHP arrays are remarkably flexible: they can hold strings, integers, objects, or even other arrays.

There are two primary ways to organize this data:

  1. Indexed Arrays: The most common form, where each value is assigned a numeric index, starting at 0.
  2. Associative Arrays: Where you define custom "keys" (strings or integers) to label your values, making the data more readable.

Creating Indexed Arrays

Indexed arrays are perfect for lists where the order matters, like a sequence of tasks or a list of category names. You create them using the array() function or the modern [] shorthand.

PHP
#6A9955">// Creating an indexed array
$tasks = ['Build Database', 'Create Controller', 'Write Views'];

#6A9955">// Accessing an element by its index
echo $tasks[0]; #6A9955">// Outputs: Build Database
echo $tasks[2]; #6A9955">// Outputs: Write Views

In this example, $tasks holds three strings. PHP automatically assigns index 0 to the first item, 1 to the second, and so on. Note that accessing an index that doesn't exist will trigger a notice in older versions of PHP or an error in stricter environments, so always ensure your index is within the bounds of the array.

Leveraging Associative Arrays

When you need to represent an entity—like a user profile—numeric indices become confusing. If you have $user = ['John', 'john@example.com', 25], you have to remember that index 1 is the email. Associative arrays allow you to name these positions.

PHP
#6A9955">// Creating an associative array
$user = [
    'name'  => 'John Doe',
    'email' => 'john@example.com',
    'age'   => 25
];

#6A9955">// Accessing elements by their custom key
echo $user['name'];  #6A9955">// Outputs: John Doe
echo $user['email']; #6A9955">// Outputs: John@example.com

This structure makes your code self-documenting. If you are building an MVC application, you will frequently use associative arrays to pass data from your models to your views.

Hands-on Exercise: Building a Product Catalog

To advance our project, let's create a simple array representation of a product.

  1. Create a new file named product.php.
  2. Define an associative array named $product with keys: title, price, and stock.
  3. Add an indexed array named $tags that contains three categories (e.g., "Electronics", "Sale", "New").
  4. Output the product title and the first tag using echo.
PHP
$product = [
    'title' => 'Mechanical Keyboard',
    'price' => 99.99,
    'stock' => 15
];

$tags = ['Electronics', 'Sale', 'New'];

echo "Product: " . $product['title'] . "\n";
echo "First Category: " . $tags[0];

Common Pitfalls

  • The Off-by-One Error: New developers often forget that indexing starts at 0. If your array has 3 items, the indices are 0, 1, and 2. Attempting to access $tasks[3] will result in an "Undefined array key" warning.
  • Mixing Keys: While PHP allows you to mix numeric and string keys in the same array, it is considered bad practice. Stick to one style per array to keep your data structures predictable.
  • Quote Mismatches: When accessing associative arrays, always use quotes around the key (e.g., $user['name']). Using $user[name] without quotes will cause PHP to look for a constant named name, which usually leads to errors.

FAQ

Can I change an array after creating it? Yes. You can add new elements by assigning a value to a new key: $user['role'] = 'admin';.

What happens if I use a duplicate key? In an associative array, the last assigned value for a specific key will overwrite any previous values associated with that same key.

How do I know if a key exists? You can use the array_key_exists('key', $array) function to check for existence before accessing the value, helping you avoid errors.

Recap

We’ve covered the foundation of data storage in PHP. You now know how to:

  • Define indexed arrays for sequential lists.
  • Create associative arrays for named data points.
  • Access these values using indices and keys.

These structures are the building blocks for the data models we will use in our Project Structure Strategy.

Up next: We will explore how to group these collections into Multidimensional Arrays to handle more complex, nested data structures.

Similar Posts