๐Ÿ“ Web Development

PHP Arrays: Lists, Keys and the Functions You Need

Aug 16, 20265 min read6 viewsBy Flow

PHP arrays hold a whole group of values under one name. A variable holds one thing. But most real data comes in groups: a list of products, the fields of a form, the rows of a database.

PHP arrays tutorial cover: lists, keys and array functions

Making an array

The short syntax is square brackets. Use it.

<?php
$languages = ["PHP", "JavaScript", "Python"];

echo $languages[0];
echo "<br>";
echo $languages[2];
?>

Output:

PHP arrays output showing the first and third items of an indexed array, PHP and Python

Counting starts at zero. The first item is [0]. The second is [1]. The third is [2].

This feels wrong for about a week, then becomes invisible. Nearly every language does it this way.

You will also meet array("PHP", "JavaScript") in older code. It does the same thing. Brackets are the modern form.

Adding and changing items

<?php
$languages = ["PHP", "JavaScript"];

$languages[] = "Python";     // add to the end
$languages[0] = "PHP 8";     // replace the first item

print_r($languages);
?>

Output:

PHP arrays print_r output after appending Python and replacing the first item with PHP 8

Empty brackets mean "put this at the end, wherever the end is". You never have to count the length yourself. That is exactly what you want when the array is built inside a loop.

print_r() prints the whole structure. It is the fastest way to see what an array really holds, and you will lean on it while learning. var_dump() shows the same thing with types included.

Associative PHP arrays

Numbers are fine for a plain list. They are useless when each value means something specific. Associative arrays let you name the slots.

<?php
$user = [
    "name"  => "Ayesha",
    "email" => "ayesha@example.com",
    "age"   => 24
];

echo $user["name"];
echo "<br>";
echo $user["age"];
?>

Output:

Associative PHP arrays output printing the name Ayesha and the age 24

The => arrow joins a key to its value.

Now $user["email"] tells you what it holds. $user[1] would have told you nothing.

This is not a rare case. Data from a database, a form, or an API arrives like this almost every time. You will spend more of your PHP life in these than in numbered ones.

Nested PHP arrays

An array can hold other arrays. That is how you store a table: a list of rows, each row a set of fields.

<?php
$students = [
    ["name" => "Ali",   "marks" => 82],
    ["name" => "Sara",  "marks" => 91],
    ["name" => "Bilal", "marks" => 68]
];

echo $students[1]["name"];
?>

Output:

Nested PHP arrays output printing Sara, the name of the second student

Read the brackets left to right. [1] picks the second student. Then ["name"] picks that student's name.

It looks harder than it is. Each bracket just steps one level deeper.

Looping through PHP arrays

Here the last lesson pays off. foreach was made for exactly this.

<?php
$students = [
    ["name" => "Ali",   "marks" => 82],
    ["name" => "Sara",  "marks" => 91],
    ["name" => "Bilal", "marks" => 68]
];

foreach ($students as $student) {
    echo $student["name"] . " scored " . $student["marks"] . "<br>";
}
?>

Output:

Looping PHP arrays with foreach: Ali scored 82, Sara scored 91, Bilal scored 68

Three lines produce a report of any length. Add fifty more students and this code does not change at all. That is the whole point.

PHP arrays functions worth knowing now

PHP ships with dozens. These are the ones you will actually reach for early on.

<?php
$numbers = [8, 3, 15, 4, 42];

echo count($numbers);
echo "<br>";
echo max($numbers);
echo "<br>";
echo min($numbers);
echo "<br>";
echo array_sum($numbers);
echo "<br>";
echo implode(", ", $numbers);
?>

Output:

PHP arrays functions output: count 5, max 42, min 3, sum 72 and the imploded list

implode() is quietly one of the most useful. It turns an array into text with a separator you choose. That is how you print a comma separated list without a loop, and without trimming a stray comma off the end.

Its opposite is explode(). That cuts text into an array.

<?php
$tags = explode(",", "php,mysql,html");

print_r($tags);
?>

Output:

PHP arrays from explode: the string php,mysql,html split into three items

Two more you will want soon. sort() arranges the values. in_array() tells you whether something is there.

<?php
$fruits = ["banana", "apple", "cherry"];

sort($fruits);
print_r($fruits);

var_dump(in_array("apple", $fruits));
?>

Output:

Sorting PHP arrays with sort, and in_array returning true for apple

Notice something about sort(). It does not hand back a new array. It rearranges the one you gave it.

So $sorted = sort($fruits); does not work. That leaves true in $sorted, not a list. This catches almost everyone once.

Three mistakes with PHP arrays

Forgetting that arrays start at zero. The last item of a five item array is [4], not [5]. Ask for [5] and you get a warning and nothing useful.

Using a key that is not there. $user["phone"] on an array with no phone raises a warning. Check with isset() first, or use $user["phone"] ?? "not given" from lesson four.

Expecting sort to return a copy. Most PHP sorting functions change the original and return only true or false.

Common questions about PHP arrays

The array questions that come up again and again once you start using them for real.

Why does sort() return true instead of the sorted array?

Because sort() rearranges the array you gave it and returns only true or false to say whether it worked. So $sorted = sort($fruits); leaves true in $sorted. Call sort($fruits); on its own line, then use $fruits โ€” it is already sorted.

What is the difference between an indexed and an associative array in PHP?

An indexed array is numbered automatically starting at 0, so you reach items with $list[0]. An associative array uses keys you choose, so you reach items with $user["name"]. Use indexed for a plain list, associative when each value means something specific.

How do I check if a key exists in a PHP array?

Use isset($user["phone"]), or array_key_exists("phone", $user) if the value might legitimately be null. Reading a missing key directly raises a warning and gives you nothing useful.

Why do PHP arrays start at 0 and not 1?

Historically the index is an offset from the start of the array, so the first item sits 0 steps in. It means the last item of a five item array is [4], not [5] โ€” the single most common off-by-one mistake.

What is next

PHP arrays are the backbone of nearly every script you will write. You can now store single values and groups, make decisions, and repeat work. The next step is packaging logic so you can reuse it by name. That means functions.

Walk back through PHP loops if foreach still feels new, or start again from PHP basics.

Comments

Loading comments...

Link copied to clipboard