Skip to main content
PHP for Beginners
CHAPTER 10 Beginner

PHP Arrays

Updated: May 12, 2026
25 min read

# Chapter 10: PHP Arrays

1. Introduction

Welcome to Chapter 10! As your applications grow, you need to manage collections of data—like a list of users, items in a shopping cart, or settings for a website. Creating a separate variable for every single item ($car1, $car2, $car3) is highly inefficient and impossible to scale. The solution is the Array. An array is a special, powerful variable that can hold multiple values under a single name. In this chapter, we will master Indexed Arrays, Associative Arrays, and Multidimensional Arrays.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Create and manipulate Indexed Arrays (lists of data).
  • Create Associative Arrays (Key-Value pairs).
  • Loop through arrays effortlessly using the foreach loop.
  • Understand Multidimensional arrays (arrays inside arrays).
  • Use built-in PHP array functions to sort and manage data.

3. Indexed Arrays

An indexed array stores multiple items, and each item is automatically assigned a numerical index. Important: Indexes in programming always start at 0, not 1!
php
1234567891011
<?php
// Creating an indexed array
$fruits = array("Apple", "Banana", "Orange");

// Accessing the array using the index
echo $fruits[0]; // Outputs: Apple
echo $fruits[1]; // Outputs: Banana

// Adding a new item to the end of the array
$fruits[] = "Mango";
?>

*Modern PHP also allows creating arrays using short syntax []:* $fruits = ["Apple", "Banana", "Orange"];

4. Associative Arrays

Instead of numerical indexes, associative arrays use named Keys that you assign to the values. This is incredibly useful for representing structured data, like a user profile.
php
1234567891011
<?php
// Creating an associative array (Key => Value)
$user = [
    "username" => "john_doe",
    "email" => "john@example.com",
    "age" => 28
];

// Accessing data via the Key
echo "User&#039;s email is: " . $user['email'];
?>

5. The foreach Loop

The foreach loop is specifically designed to loop through arrays. It is the most common loop you will use in PHP. It automatically knows how many items are in the array and stops when it reaches the end.
php
1234567891011121314151617
<?php
$colors = ["Red", "Green", "Blue"];

// Looping an Indexed Array
foreach ($colors as $color) {
    echo "Color: $color <br>";
}

echo "<hr>";

// Looping an Associative Array (Accessing Key and Value)
$car = ["brand" => "Ford", "model" => "Mustang", "year" => 2024];

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

6. Multidimensional Arrays

A multidimensional array is simply an array that contains one or more arrays inside it. This is how databases return tabular data.
php
1234567891011
<?php
// An array of students, where each student is an associative array
$students = [
    ["name" => "Alice", "grade" => "A"],
    ["name" => "Bob", "grade" => "C"],
    ["name" => "Charlie", "grade" => "B"]
];

// Accessing Bob's grade: Go to index 1, then key "grade"
echo "Bob got a: " . $students[1]["grade"];
?>

7. Essential Array Functions

PHP has dozens of powerful built-in functions to manipulate arrays:
  • count($array): Returns the number of items in the array.
  • inarray("value", $array): Checks if a value exists in an array.
  • arraypush($array, "value"): Adds a value to the end.
  • sort($array): Sorts arrays in ascending order.

8. Real-World Examples

Imagine fetching a list of links from a database to generate a website's navigation menu.
php
12345678910111213141516
<?php
$nav_links = [
    "Home" => "index.php",
    "About Us" => "about.php",
    "Services" => "services.php",
    "Contact" => "contact.php"
];
?>

<nav>
    <ul>
        <?php foreach ($nav_links as $title => $url): ?>
            <li><a href="<?php echo $url; ?>"><?php echo $title; ?></a></li>
        <?php endforeach; ?>
    </ul>
</nav>

*Notice the alternate PHP syntax foreach(...): and endforeach;. This is highly preferred when mixing PHP heavily with HTML blocks.*

9. Output Explanations

In the navigation example, the foreach loop extracts the Key ($title) and the Value ($url) for every item in the $navlinks array. It injects them into the href and the anchor text of the HTML, generating a complete, dynamic navigation menu.

10. Common Mistakes

  • Forgetting that indexes start at 0: Trying to access $fruits[3] when there are 3 items will result in an "Undefined offset" warning, because the indexes are 0, 1, and 2.
  • Echoing an entire array: Writing echo $user; will throw an error (Array to string conversion). You cannot echo an array directly. You must echo specific keys, or use vardump($user) or printr($user) to inspect it.
  • Missing commas: When declaring arrays, items must be separated by commas ,.

11. Best Practices

  • Use descriptive plural names for arrays (e.g., $users, $products) to indicate they hold multiple items.
  • Use printr($array) wrapped in HTML <pre> tags for clean, readable debugging of arrays.

12. Exercises

  1. 1. Create an indexed array of 4 cities. Loop through it with foreach and echo them in an HTML list <ul>.
  1. 2. Create an associative array representing a book (title, author, pages). Echo out a sentence using that data.

13. Mini Project: Product List System

Task: Build an e-commerce product display. Use a multidimensional array to store 3 products (name, price, stock). Loop through the products and display them in HTML cards.
php
123456789101112131415161718192021222324252627282930313233
<?php
$products = [
    ["name" => "Laptop", "price" => 999.99, "in_stock" => true],
    ["name" => "Mouse", "price" => 25.00, "in_stock" => true],
    ["name" => "Keyboard", "price" => 75.50, "in_stock" => false]
];
?>
<!DOCTYPE html>
<html>
<head>
    <style>
        .product { border: 1px solid #ccc; padding: 10px; margin: 10px; width: 200px; }
        .out-of-stock { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <h2>Our Products</h2>
    <div style="display: flex;">
        <?php foreach ($products as $item): ?>
            <div class="product">
                <h3><?php echo $item[&#039;name']; ?></h3>
                <p>Price: $<?php echo $item[&#039;price']; ?></p>
                
                <?php if ($item[&#039;in_stock']): ?>
                    <button>Add to Cart</button>
                <?php else: ?>
                    <p class="out-of-stock">Out of Stock</p>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
</body>
</html>

14. Coding Challenges

Challenge 1: Create an array of numbers [10, 20, 30, 40]. Write a foreach loop that adds all the numbers together and stores the sum in a variable. Echo the final sum.
php
12345678910
<?php
// Solution
$numbers = [10, 20, 30, 40];
$sum = 0;

foreach ($numbers as $num) {
    $sum += $num;
}
echo "Total Sum: " . $sum; // Outputs 100
?>

15. MCQs with Answers

1. What is the index of the first element in an indexed PHP array? A) 1 B) 0 C) -1 D) First *Answer: B*

2. Which loop is specifically designed to iterate over arrays? A) for B) while C) do...while D) foreach *Answer: D*

3. What does an Associative Array use instead of numerical indexes? A) Objects B) Key-Value pairs C) Classes D) Functions *Answer: B*

16. Interview Questions

Q: What is a Multidimensional array? *A:* A multidimensional array is an array that contains one or more arrays as its values. It is used to store complex, structured data, such as a table of database records where each row is an array, and the entire table is stored inside a parent array.

Q: Why shouldn't you use a for loop to iterate over an associative array? *A:* A standard for loop relies on an integer counter ($i = 0, 1, 2) to access elements by numerical index. Associative arrays use string keys (like "name" or "email"), so $array[$i] will not work. The foreach loop gracefully handles string keys.

17. FAQs

Q: Can I mix data types inside a single array? *A:* Yes. In PHP, an array can simultaneously hold strings, integers, booleans, and even other arrays!

18. Summary

You have mastered data collection! You learned how to group simple data into Indexed Arrays, structure profile-like data into Associative Arrays, and build complex datasets using Multidimensional Arrays. You also unlocked the foreach loop, an essential tool for dynamically rendering data to the screen.

19. Next Chapter Recommendation

Data isn't just arrays; it is heavily text-based. Have you ever wondered how to find a word inside a paragraph, or capitalize a user's name automatically? In Chapter 11: PHP Strings, we will dive into powerful functions designed to manipulate text!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·