Arrays

PHP · Lesson 16 of 50 7 min read Updated

Real programs work with groups of things: the students in a class, the items in a cart, the rows from a database table. In PHP, you keep a group of values together in an array. Arrays are the most used data structure in PHP, so it is worth learning them well.

In this lesson you will create the two kinds of PHP arrays, read and change their items, check for keys safely, build nested arrays of records and convert between strings and arrays.

Indexed arrays

An indexed array is a numbered list. You create it with square brackets, separating the items with commas. PHP numbers the items automatically, starting from 0. Each number is called an index.

PHP
<?php
declare(strict_types=1);

$cities = ['Rohtak', 'Jaipur', 'Pune'];

echo $cities[0], "\n";
echo count($cities), " cities\n";

$cities[] = 'Kochi';
$cities[1] = 'Jodhpur';

print_r($cities);
Output
Rohtak
3 cities
Array
(
    [0] => Rohtak
    [1] => Jodhpur
    [2] => Pune
    [3] => Kochi
)

Here is what each line does:

  • $cities[0] reads the first item. The last item of a 3-item array is $cities[2], not $cities[3].
  • count() returns the number of items.
  • $cities[] = 'Kochi'; with empty brackets adds an item to the end.
  • $cities[1] = 'Jodhpur'; replaces the item at index 1.
  • print_r() prints a whole array in a readable form, which is handy while you learn. var_dump() also works and shows the types.

Associative arrays

An associative array uses names, called keys, instead of numbers. Each key points to a value. You write each pair as key => value. This is perfect for describing one thing with several properties:

PHP
<?php
declare(strict_types=1);

$student = [
    'name' => 'Priya',
    'roll' => 23,
    'city' => 'Lucknow',
];

$student['email'] = 'priya@example.com';
$student['city'] = 'Kanpur';

echo "{$student['name']} (roll {$student['roll']}) lives in {$student['city']}\n";
print_r($student);
Output
Priya (roll 23) lives in Kanpur
Array
(
    [name] => Priya
    [roll] => 23
    [city] => Kanpur
    [email] => priya@example.com
)

Assigning to a new key adds it; assigning to an existing key replaces the value. Keys keep the order in which you added them. A comma after the last item is allowed, and it makes adding lines later easier.

In PHP, indexed and associative arrays are really the same thing: an ordered map from keys to values. An indexed array just happens to have the keys 0, 1, 2 and so on. Keys can be ints or strings; a string that looks like a whole number, such as '5', is stored as the int 5.

To loop over either kind, use foreach, as you learned in Loops.

Checking keys and values safely

Reading a key that does not exist shows a warning such as Warning: Undefined array key "phone" and gives null. This happens all the time with form data and optional settings, so PHP gives you several safe checks:

  • $arr['key'] ?? 'default' reads the value or a default, with no warning.
  • isset($arr['key']) is true if the key exists and its value is not null.
  • array_key_exists('key', $arr) is true if the key exists, even when the value is null.
  • in_array($value, $arr, true) checks whether a value is in the array.
PHP
<?php
declare(strict_types=1);

$student = ['name' => 'Priya', 'roll' => 23, 'nickname' => null];
$cities = ['Rohtak', 'Jaipur', 'Pune'];

echo $student['phone'] ?? 'No phone', "\n";
var_dump(isset($student['nickname']));
var_dump(array_key_exists('nickname', $student));
var_dump(in_array('Pune', $cities, true));
var_dump(in_array('pune', $cities, true));
Output
No phone
bool(false)
bool(true)
bool(true)
bool(false)

Always pass true as the third argument of in_array(). It makes the check strict (===). Without it, PHP uses loose comparison, so in_array('1e1', ['10']) is true.

Removing items

unset() removes an item. In an indexed array, the other items keep their indexes, which leaves a gap. If you need a clean 0, 1, 2 list again, pass the array through array_values():

PHP
<?php
declare(strict_types=1);

$queue = ['Aarav', 'Isha', 'Farhan', 'Ananya'];
unset($queue[1]);
print_r($queue);

$queue = array_values($queue);
print_r($queue);
Output
Array
(
    [0] => Aarav
    [2] => Farhan
    [3] => Ananya
)
Array
(
    [0] => Aarav
    [1] => Farhan
    [2] => Ananya
)

After unset(), there is no index 1, so a for loop counting from 0 to count($queue) - 1 would hit a missing key. foreach does not care about gaps, which is one more reason to prefer it.

Arrays of records

An array can hold other arrays. The most common shape in PHP is a list of records: an indexed array where each item is an associative array. Database results arrive in exactly this shape, as you will see in CRUD with Prepared Statements.

PHP
<?php
declare(strict_types=1);

$students = [
    ['name' => 'Aarav', 'city' => 'Rohtak', 'marks' => 81],
    ['name' => 'Meera', 'city' => 'Kochi', 'marks' => 94],
    ['name' => 'Kabir', 'city' => 'Jaipur', 'marks' => 67],
];

echo $students[1]['name'], "\n";

foreach ($students as $student) {
    echo "{$student['name']} from {$student['city']}: {$student['marks']}\n";
}
Output
Meera
Aarav from Rohtak: 81
Meera from Kochi: 94
Kabir from Jaipur: 67

Read $students[1]['name'] from left to right: take item 1 of the list (the second student), then take its name key.

Strings to arrays and back

explode() splits a string into an array at every separator. implode() joins an array into a string with a separator between the items. You will use them for comma-separated values, tags and simple lists:

PHP
<?php
declare(strict_types=1);

$subjects = explode(',', 'Maths,Science,English,Hindi');
echo count($subjects), " subjects\n";
echo $subjects[2], "\n";

$subjects[] = 'Computer Science';
echo implode(' | ', $subjects), "\n";
Output
4 subjects
English
Maths | Science | English | Hindi | Computer Science

Common mistakes

  • Forgetting that indexes start at 0. The last item is at count($arr) - 1.
  • Reading a key that may be missing. Use ?? or isset() instead of reading it directly.
  • Using in_array() without true. Loose comparison gives surprising matches.
  • Expecting unset() to renumber the array. Use array_values() if you need clean indexes.
  • Mixing up keys and values. isset() and array_key_exists() check keys; in_array() checks values.

Key points

  • Indexed arrays number their items from 0; associative arrays use your own keys.
  • Add to the end with $arr[] = $value; add or replace a key with $arr['key'] = $value.
  • count() gives the number of items; print_r() and var_dump() show the contents.
  • Read optional keys with ??, check them with isset() or array_key_exists(), and find values with in_array($v, $arr, true).
  • unset() removes an item but leaves a gap; array_values() renumbers.
  • A list of associative arrays is the standard shape for records.
  • explode() and implode() convert between strings and arrays.

Exercise

Create a list of three products, each an associative array with name, price and stock. Use a tablet for ₹14,999 with 5 in stock, earphones for ₹1,299 with 0 in stock, and a power bank for ₹1,799 with 12 in stock. Loop over the list and print each product with its price, adding "(out of stock)" when stock is 0. Then add a fourth product with $products[] = [...] and print how many products there are now.

Show solution
PHP
<?php
declare(strict_types=1);

$products = [
    ['name' => 'Tablet', 'price' => 14999, 'stock' => 5],
    ['name' => 'Earphones', 'price' => 1299, 'stock' => 0],
    ['name' => 'Power bank', 'price' => 1799, 'stock' => 12],
];

foreach ($products as $product) {
    $note = $product['stock'] === 0 ? ' (out of stock)' : '';
    echo "{$product['name']}: ₹{$product['price']}$note\n";
}

$products[] = ['name' => 'Phone cover', 'price' => 299, 'stock' => 40];
echo count($products), " products\n";
Output
Tablet: ₹14999
Earphones: ₹1299 (out of stock)
Power bank: ₹1799
4 products

Each product is an associative array inside an indexed list. The ternary picks the extra note, and $products[] = [...] appends a whole new record.

Quick Quiz

1. What is the index of the first item in a PHP indexed array?

2. Which check returns true for a key whose value is null?

3. What does implode(', ', ['Pune', 'Kochi']) return?

4. After $a = ['x', 'y', 'z']; unset($a[0]);, what is the first key of $a?

Learn PHP with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call