PHP arrays matters once your pages get past the basics. How to store and work with lists of related values in one variable.
What are arrays?
An array is a variable that holds more than one value. Use one for product names, user details, or any collection of related data.
Types of arrays in PHP
PHP has three kinds:
- Indexed arrays – numeric keys (0, 1, 2…).
- Associative arrays – named string keys.
- Multidimensional arrays – arrays inside arrays.
Creating indexed arrays
The simplest form uses numeric indexes:
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[0]; // Outputs 'Apple'
?>
You can also append values without calling array():
<?php
$fruits[] = "Apple";
$fruits[] = "Banana";
$fruits[] = "Cherry";
?>
Associative arrays
Associative arrays use string keys instead of numbers. That makes the data easier to read and access.
<?php
$age = array("Alice" => "25", "Bob" => "35", "Charlie" => "40");
echo "Alice is " . $age['Alice'] . " years old.";
?>
Multidimensional arrays
An array can contain other arrays. Handy when you need structured data – contacts, settings, rows from a database.
<?php
$contacts = array(
array(
"name" => "Alice",
"email" => "alice@example.com"
),
array(
"name" => "Bob",
"email" => "bob@example.com"
)
);
echo "Email of Bob is " . $contacts[1]["email"];
?>
Looping through arrays
Most of the time you’ll loop over an array to run the same code for each item.
The foreach loop
foreach is the usual choice. Simple and readable.
<?php
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
With associative arrays, grab both key and value:
<?php
foreach ($age as $name => $age) {
echo "$name is $age years old.<br>";
}
?>
The for loop
Indexed arrays also work with a plain for loop:
<?php
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "<br>";
}
?>
Sorting arrays
PHP has built-in sort functions for ascending, descending, and sorting associative arrays by key or value:
<?php
sort($fruits); // Sorts $fruits in ascending order
rsort($fruits); // Sorts $fruits in descending order
asort($age); // Sorts $age by value in ascending order
ksort($age); // Sorts $age by key in ascending order
?>
Practical example: a simple contact list
Here’s a multidimensional associative array looped out as a contact list:
<?php
$contacts = array(
"Alice" => array(
"phone" => "123-456-7890",
"email" => "alice@example.com"
),
"Bob" => array(
"phone" => "987-654-3210",
"email" => "bob@example.com"
)
);
foreach ($contacts as $name => $info) {
echo "$name's contact details:<br>";
echo "Phone: " . $info["phone"] . "<br>";
echo "Email: " . $info["email"] . "<br><br>";
}
?>
Arrays are one of the main ways PHP handles grouped data. Once you’re comfortable with the three types and a few loop patterns, most list-and-table problems get much simpler.

