What is an Array?

So far, every variable we've created has held only one piece of information (one number or one string). But what if you need to store a list of items, like a list of usernames or product names? An array is a special type of variable that allows you to store multiple values in a single variable.

Think of it like a grocery list. Instead of having a separate piece of paper for each item, you have one list that contains all of them.


1. Indexed Arrays

This is the most common type of array. It's an ordered list where each item has a numeric position, called an index. The most important thing to remember is that in PHP (and most programming languages), indexing starts at 0, not 1.

<?php
    // Creating an indexed array using modern shorthand syntax []
    $cars = ["Volvo", "BMW", "Toyota"];

    // Accessing elements using their index
    echo $cars[0]; // Outputs: Volvo
    echo "<br>";
    echo $cars[2]; // Outputs: Toyota
?>

2. Associative Arrays

Sometimes, using numbers as an index isn't very descriptive. An associative array lets you use named keys that you define instead of numbers. This is like a dictionary, where you look up a word (the key) to find its definition (the value).

You use the => operator to associate a key with a value.

<?php
    // Creating an associative array
    $user = [
        "firstName" => "John",
        "lastName" => "Doe",
        "age" => 35
    ];

    // Accessing elements using their named keys
    echo "User's age is: " . $user["age"]; // Outputs: User's age is: 35
?>

3. Looping Through Arrays with foreach

Manually accessing each element of a large array would be tedious. The foreach loop is designed specifically to iterate over every item in an array, making it incredibly easy to work with lists of data.

Looping through an Indexed Array:

<?php
    $colors = ["Red", "Green", "Blue"];

    foreach ($colors as $color) {
        echo $color . "<br>";
    }
?>

Looping through an Associative Array:

<?php
    $user_data = [
        "name" => "Jane Smith",
        "email" => "jane@example.com"
    ];

    foreach ($user_data as $key => $value) {
        echo $key . ": " . $value . "<br>";
    }
?>

A Quick Tip for Developers: print_r()

You cannot use echo to display a whole array. If you want to see the entire structure and contents of an array for debugging purposes, the print_r() function is your best friend.

<?php
    $fruits = ["Apple", "Banana", "Cherry"];
    print_r($fruits);
?>

Congratulations! You've now learned all the fundamental building blocks of PHP. You understand variables, operators, control structures, functions, and arrays. With this knowledge, you are ready to move on to Part 2, where we'll start building real web application features!