LearnContact
Lesson 2024 min read

Arrays

Learn how to create, modify, and loop over indexed and associative arrays, PHP's core tool for storing collections of data.

Introduction

So far, every variable you have used has held a single value — one string, one number, one boolean. Real programs, though, constantly need to work with collections: a list of products, a set of student names, a group of settings. PHP's answer to this is the array.

This lesson introduces PHP arrays: the difference between indexed arrays (ordered lists) and associative arrays (named key-value pairs), how to create and add to arrays, the most commonly used array functions, and how to loop over an array's contents with foreach.

What You Will Learn
  • What an array is and why it is useful.
  • The difference between indexed arrays and associative arrays.
  • How to create arrays with the [] short syntax.
  • How to add new elements to an array with $arr[] = value.
  • Common array functions: count(), array_push(), array_merge(), sort(), and in_array().
  • How to loop over an array's values (and keys) with foreach.

What is an Array?

An array is a single variable that can hold multiple values at once. Instead of creating $student1, $student2, $student3, you can store all of them together in one array and work with them as a group — looping over them, counting them, sorting them, and more.

Two Kinds of Arrays in PHP
  • Indexed arrays: values are ordered and accessed by a numeric position, starting at 0.
  • Associative arrays: values are accessed by a named key instead of a number, like a dictionary.

Indexed Arrays

An indexed array stores a list of values where each one is automatically assigned a numeric key, starting at 0 for the first element, 1 for the second, and so on. You create one using square brackets [].

indexed-arrays.php
<?php
$fruits = ["Apple", "Banana", "Cherry"];

echo $fruits[0] . "\n";
echo $fruits[1] . "\n";
echo $fruits[2] . "\n";

echo "There are " . count($fruits) . " fruits.\n";
?>
Output
Apple
Banana
Cherry
There are 3 fruits.
Arrays Start at Index 0

The first element of an indexed array is always at position 0, not 1. Trying to access $fruits[3] in the example above would trigger an "undefined array key" warning, since valid indexes are only 0, 1, and 2.

Associative Arrays

An associative array uses named keys instead of automatic numeric ones, letting you label each value with something meaningful — much like a real-world dictionary or a JSON object. You define one using key => value pairs.

associative-arrays.php
<?php
$student = [
    "name" => "Priya",
    "age" => 21,
    "course" => "Computer Science",
];

echo $student["name"] . "\n";
echo $student["age"] . "\n";
echo $student["course"] . "\n";
?>
Output
Priya
21
Computer Science
When to Use Which

Use an indexed array for a simple ordered list, like a list of tags or scores. Use an associative array when each value has a distinct meaning tied to a name, like a single record with a "name", "age", and "email".

Adding Elements to an Array

You can add a new element to the end of an indexed array using the $arr[] = value shorthand — PHP automatically assigns the next available numeric key. For an associative array, simply assign a value to a new key.

adding-elements.php
<?php
$fruits = ["Apple", "Banana"];
$fruits[] = "Cherry";
$fruits[] = "Mango";

print_r($fruits);

$student = ["name" => "Priya"];
$student["age"] = 21;
$student["course"] = "Computer Science";

print_r($student);
?>
Output
Array
(
    [0] => Apple
    [1] => Banana
    [2] => Cherry
    [3] => Mango
)
Array
(
    [name] => Priya
    [age] => 21
    [course] => Computer Science
)

Common Array Functions

PHP has an enormous library of built-in array functions. A handful of them will cover the vast majority of everyday needs.

array-functions.php
<?php
$numbers = [5, 2, 9, 1];

echo count($numbers) . "\n";

array_push($numbers, 20, 30);
print_r($numbers);

$more = [100, 200];
$combined = array_merge($numbers, $more);
print_r($combined);

sort($combined);
print_r($combined);

var_dump(in_array(9, $combined));
var_dump(in_array(999, $combined));
?>
Output
4
Array
(
    [0] => 5
    [1] => 2
    [2] => 9
    [3] => 1
    [4] => 20
    [5] => 30
)
Array
(
    [0] => 5
    [1] => 2
    [2] => 9
    [3] => 1
    [4] => 20
    [5] => 30
    [6] => 100
    [7] => 200
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 5
    [3] => 9
    [4] => 20
    [5] => 30
    [6] => 100
    [7] => 200
)
bool(true)
bool(false)
FunctionDescription
count($arr)Returns the number of elements in an array.
array_push($arr, ...$values)Adds one or more elements to the end of an array.
array_merge($arr1, $arr2)Combines two or more arrays into one.
sort($arr)Sorts an array's values in ascending order and re-indexes the keys.
in_array($value, $arr)Checks whether a value exists anywhere in an array.
array_push() vs $arr[]

array_push($arr, $value) and $arr[] = $value do the same thing for a single value. The short [] syntax is generally preferred because it avoids a function call, but array_push() is convenient when adding several values at once.

Looping With foreach

The foreach loop is the standard way to iterate over every element in an array, whether indexed or associative. For an indexed array, you get each value in order; for an associative array, you can also grab the key alongside the value.

foreach-indexed.php
<?php
$fruits = ["Apple", "Banana", "Cherry"];

foreach ($fruits as $fruit) {
    echo "I like $fruit\n";
}
?>
Output
I like Apple
I like Banana
I like Cherry
foreach-associative.php
<?php
$student = [
    "name" => "Priya",
    "age" => 21,
    "course" => "Computer Science",
];

foreach ($student as $key => $value) {
    echo "$key: $value\n";
}
?>
Output
name: Priya
age: 21
course: Computer Science

Common Mistakes

Avoid These Mistakes
  • Forgetting that indexed arrays start at 0, not 1.
  • Accessing an array key that does not exist, triggering an "undefined array key" warning.
  • Using sort() on an associative array — it re-indexes with numeric keys and discards the original named keys.
  • Confusing array_merge() with the + operator — they handle duplicate string keys differently.

Best Practices

  • Use descriptive, lowercase key names in associative arrays, like "first_name" rather than "FN".
  • Prefer $arr[] = $value for adding a single element; use array_push() only when adding multiple at once.
  • Use count() before looping with a numeric index-based for loop, or simply use foreach when order-based indexing is not needed.
  • Check array_key_exists() or isset() before accessing a key that might not be present.

Frequently Asked Questions

Can an array mix indexed and associative keys?

Yes — PHP arrays are flexible and can technically mix numeric and string keys in the same array, though it is best practice to keep an array consistently one type or the other for clarity.

What happens if I use a key that already exists?

Assigning a value to an existing key simply overwrites the previous value at that key; it does not create a duplicate entry.

Does foreach modify the original array?

By default, no — foreach works on a copy of each value. If you need to modify the original array while looping, you can loop by reference using foreach ($arr as &$value).

How do I check how many elements are in an array?

Use count($arr), which returns the total number of elements regardless of whether the array is indexed or associative.

What is the difference between sort() and asort()?

sort() re-indexes the array with new numeric keys after sorting, discarding original keys. asort() sorts by value but preserves the original key-value associations — important for associative arrays.

Key Takeaways

  • Arrays store multiple values in a single variable.
  • Indexed arrays use automatic numeric keys starting at 0; associative arrays use named keys.
  • The [] short syntax creates arrays, and $arr[] = value appends a new element.
  • count(), array_push(), array_merge(), sort(), and in_array() cover most everyday array needs.
  • foreach is the standard way to loop over an array's values, or its keys and values together.

Summary

Arrays let you group related data together and work with it as a collection instead of juggling many separate variables.

In this lesson, you learned the difference between indexed and associative arrays, how to create and add to them, the most common array functions, and how to loop through an array with foreach. Next, you will learn about multidimensional arrays — arrays that contain other arrays.

Lesson 20 Completed
  • You understand the difference between indexed and associative arrays.
  • You can add elements to an array using the [] shorthand.
  • You know the most commonly used array functions.
  • You can loop over any array using foreach.
Next Lesson →

Multidimensional Arrays