MasterPHP.in
PHP Tutorial

PHP Arrays Explained


What is an Array?

An array is a single variable that can hold multiple values at once, instead of storing just one value the way a regular variable does. Arrays are one of the most fundamental and heavily used data structures in PHP, since almost any real application needs to work with lists of things — products, users, orders, form fields, or menu items.


php

<?php
$name = "Rohan"; // a regular variable holds one value

$fruits = ["Apple", "Banana", "Mango"]; // an array holds multiple values

Creating an Array

PHP offers two ways to write an array, both functionally identical:


php

<?php
// Short syntax (modern, most commonly used)
$fruits = ["Apple", "Banana", "Mango"];

// Long syntax (older style, still valid)
$fruits = array("Apple", "Banana", "Mango");

The short syntax using square brackets has become the standard in modern PHP code, and is generally what you'll see in current tutorials, documentation, and real-world projects.


Indexed Arrays

The simplest type of array is an indexed array, where each value is automatically assigned a numeric position, called an index, starting from 0.


php

<?php
$fruits = ["Apple", "Banana", "Mango"];

echo $fruits[0]; // Apple
echo $fruits[1]; // Banana
echo $fruits[2]; // Mango

This zero-based numbering trips up many beginners at first — the first element is at position 0, not 1. Trying to access $fruits[3] in the example above would trigger an "undefined array key" warning, since only positions 0, 1, and 2 exist.


Modifying Indexed Arrays


php

<?php
$fruits = ["Apple", "Banana", "Mango"];

$fruits[1] = "Blueberry"; // replaces "Banana"
print_r($fruits); // ["Apple", "Blueberry", "Mango"]

$fruits[] = "Orange"; // adds to the end automatically
print_r($fruits); // ["Apple", "Blueberry", "Mango", "Orange"]

Using empty square brackets ($fruits[]) is a common shorthand for appending a new value to the end of an array without needing to know its next index manually.


Associative Arrays

An associative array uses named keys instead of numeric positions, which makes the data more descriptive and easier to work with when each value has a clear label.


php

<?php
$user = [
    "name" => "Rohan",
    "age" => 28,
    "city" => "Mumbai"
];

echo $user['name']; // Rohan
echo $user['age'];  // 28

The => symbol (sometimes called the "arrow") connects each key to its corresponding value. Keys can be strings (as shown here) or integers, but using descriptive string keys is what makes associative arrays so useful for representing structured information, like a single user's details.


Modifying Associative Arrays


php

<?php
$user = ["name" => "Rohan", "age" => 28];

$user['age'] = 29;           // update an existing key
$user['city'] = "Mumbai";    // add a new key

print_r($user);
// ["name" => "Rohan", "age" => 29, "city" => "Mumbai"]

unset($user['city']);        // remove a key entirely
print_r($user);
// ["name" => "Rohan", "age" => 29]

Multidimensional Arrays

An array can contain other arrays as its values, creating a multidimensional array. This is extremely common in real applications for representing lists of structured records, like multiple users or products.


php

<?php
$users = [
    ["name" => "Rohan", "age" => 28],
    ["name" => "Priya", "age" => 24],
    ["name" => "Aman", "age" => 32],
];

echo $users[0]['name']; // Rohan
echo $users[1]['age'];  // 24

Here, $users is an indexed array where each element is itself an associative array. This nested structure closely mirrors how data is typically returned from a database — a list of rows, where each row has named columns.


Iterating Over Arrays

While loops are covered in detail in an earlier lesson, it's worth seeing how naturally foreach pairs with arrays, since this combination is used constantly in real code.


php

<?php
$fruits = ["Apple", "Banana", "Mango"];

foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

$user = ["name" => "Rohan", "age" => 28];

foreach ($user as $key => $value) {
    echo "$key: $value\n";
}

Checking Array Contents

A few quick checks come up constantly when working with arrays:


php

<?php
$fruits = ["Apple", "Banana", "Mango"];

echo count($fruits);              // 3 - number of elements
var_dump(isset($fruits[1]));      // true - checks if a specific index/key exists
var_dump(empty($fruits));         // false - array has content
var_dump(is_array($fruits));      // true - confirms the variable is an array

Indexed vs Associative: Choosing the Right One


Situation                                      Array Type
------------------------------------------------------------
Order matters, no labels needed                 Indexed
(e.g. a simple list of fruits)

Each value needs a clear, named label            Associative
(e.g. representing a single user's details)

A list of multiple structured records            Multidimensional
(e.g. many users, many products)                 (indexed array of
                                                  associative arrays)

A Common Beginner Mistake: Confusing Keys and Values


php

<?php
$fruits = ["Apple", "Banana", "Mango"];

foreach ($fruits as $key => $value) {
    echo "$key => $value\n";
}
// Output:
// 0 => Apple
// 1 => Banana
// 2 => Mango

This example is worth studying closely: even an indexed array technically has keys — they're just automatically assigned numbers rather than custom names. Understanding this helps make sense of functions and behaviors that reference "keys," even when you're working with a simple indexed list rather than an associative array.


What's Next

With the fundamentals of arrays covered, the next lesson dives into PHP's extensive library of built-in array functions, sorting, filtering, and transforming array data efficiently, followed by a lesson showing how arrays are used to solve real, practical problems in actual applications.

Frequently Asked Questions

This is a convention PHP shares with most programming languages, rooted in how arrays are handled at a lower technical level (the index represents an offset from the start of the array, and the first element has an offset of zero). It's simply something to memorize early on.
An indexed array uses automatically assigned numeric positions to access its values, while an associative array uses custom, named keys instead. Associative arrays are preferred when each value needs a clear, descriptive label.
Yes. A single PHP array can hold strings, integers, booleans, other arrays, or a mix of all of them simultaneously — PHP doesn't require every element in an array to be the same type.
PHP will trigger an "undefined array key" warning and return null for that access attempt, rather than stopping the script entirely. It's good practice to check with isset() first when you're unsure whether a key exists.
Multidimensional arrays are commonly used to represent multiple structured records at once, such as a list of users, products, or orders, where each individual record is itself an associative array of details. This structure closely resembles how data is returned from database queries.

Share this tutorial