Skip to content

PHP Arrays

Arrays are a collection of elements that are stored in a single variable. PHP supports several types of arrays that allow you to store multiple values in an organized way.


PHP supports three main types of arrays, each serving a different purpose.

  1. Indexed Arrays: Arrays with numeric keys.
  2. Associative Arrays: Arrays with named keys (key-value pairs).
  3. Multidimensional Arrays: Arrays containing other arrays.

This is the simplest type of array. It’s an ordered list where each value is identified by a numeric index, which starts at 0.

You can use the modern short array syntax [] (recommended) or the older array() constructor.

// Method 1: Using array() function
$fruits = array("apple", "banana", "orange");
// Method 2: Using short array syntax (PHP 5.4+)
$fruits = ["apple", "banana", "orange"];
// Method 3: Manual assignment
$fruits[0] = "apple";
$fruits[1] = "banana";
$fruits[2] = "orange";

You access an element by referring to its index number inside square brackets [].

<?php
$colors = ["Red", "Green", "Blue"];
// Remember, the index starts at 0!
echo $colors[0]; // Outputs: Red
echo "<br>";
echo $colors[2]; // Outputs: Blue
// You can also modify an element
$colors[1] = "Yellow";
echo "<br>";
echo $colors[1]; // Outputs: Yellow
// To add a new element to the end of the array
$colors[] = "Purple";
// The $colors array is now ["Red", "Yellow", "Blue", "Purple"]
?>

  • Associative arrays use named keys instead of numeric indices.
  • They are the foundation of how PHP handles form data ($_POST, $_GET) and much more.
  • Instead of using numeric indexes, you assign a custom key (a string) to each value.

The syntax uses => to associate a key with a value.

// Method 1: Using array() function
$person = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York"
);
// Method 2: Using short array syntax (PHP 5.4+)
$person = [
"name" => "John Doe",
"age" => 30,
"city" => "New York"
];
// Method 3: Manual assignment
$person["name"] = "John Doe";
$person["age"] = 30;
$person["city"] = "New York";

You access elements using their unique string keys.

<?php
$user = [
"firstName" => "John",
"lastName" => "Doe",
"email" => "john.doe@example.com"
];
echo "User's email is: " . $user["email"]; // Outputs: User's email is: john.doe@example.com
// Modifying a value
$user["email"] = "j.doe@newdomain.com";
// Adding a new key-value pair
$user["city"] = "New York";
?>

Good practice: Type hinting and checking if key exists.
// Good practice: Type hinting
function processNumbers(array $numbers): array {
return array_map(function($n) {
return $n * 2;
}, $numbers);
}
// Good practice: Check if key exists
if (isset($person["email"])) {
echo $person["email"];
} else {
echo "Email not provided";
}

A multidimensional array is an array that contains one or more other arrays. This is perfect for representing complex data structures like a list of products where each product has its own properties, or rows of data from a database table.

// 2D Array
$students = [
["John", 85, "Math"],
["Jane", 92, "Science"],
["Bob", 78, "History"]
];
// Associative multidimensional array
$products = [
"laptop" => [
"brand" => "Dell",
"price" => 800,
"specs" => ["RAM" => "8GB", "Storage" => "256GB SSD"]
],
"phone" => [
"brand" => "iPhone",
"price" => 999,
"specs" => ["RAM" => "6GB", "Storage" => "128GB"]
]
];
// Accessing 2D array
echo $students[0][0]; // Output: John
echo $students[1][2]; // Output: Science
// Accessing associative multidimensional array
echo $products["laptop"]["brand"]; // Output: Dell
echo $products["phone"]["specs"]["RAM"]; // Output: 6GB

$fruits = ["apple", "banana"];
// Add to end
$fruits[] = "orange";
array_push($fruits, "grape", "mango");
// Add to beginning
array_unshift($fruits, "strawberry");
// Add at specific index (associative)
$fruits["tropical"] = "pineapple";

$fruits = ["apple", "banana", "orange", "grape"];
// Remove last element
$lastFruit = array_pop($fruits);
// Remove first element
$firstFruit = array_shift($fruits);
// Remove specific element by key
unset($fruits[1]);
// Remove specific value
$key = array_search("orange", $fruits);
if ($key !== false) {
unset($fruits[$key]);
}

$numbers = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . " ";
}

The most common task you’ll perform with an array is to loop through it and do something with each element. The foreach loop is designed specifically for this.

<?php
// Looping through an indexed array
$colors = ["Red", "Green", "Blue"];
echo "<ul>";
foreach ($colors as $color) {
echo "<li>" . $color . "</li>";
}
echo "</ul>";
// Looping through an associative array to get both key and value
$user = [
"First Name" => "John",
"Last Name" => "Doe",
"Email" => "john.doe@example.com"
];
echo "<h3>User Details</h3>";
foreach ($user as $key => $value) {
echo "<strong>" . $key . ":</strong> " . $value . "<br>";
}
?>
$fruits = ["apple", "banana", "orange"];
$i = 0;
while ($i < count($fruits)) {
echo $fruits[$i] . " ";
$i++;
}

$fruits = ["apple", "banana", "orange"];
// Get array length
$length = count($fruits); // 3
// Check if array is empty
$isEmpty = empty($fruits); // false
// Check if key exists
$keyExists = array_key_exists("name", $person); // true/false
// Check if value exists
$valueExists = in_array("apple", $fruits); // true

$numbers = [3, 1, 4, 1, 5, 9];
// Sort array
sort($numbers); // [1, 1, 3, 4, 5, 9]
// Reverse array
$reversed = array_reverse($numbers);
// Get unique values
$unique = array_unique($numbers);
// Filter array
$evenNumbers = array_filter($numbers, function($n) {
return $n % 2 == 0;
});
// Map array (transform each element)
$doubled = array_map(function($n) {
return $n * 2;
}, $numbers);

$array1 = ["a", "b", "c"];
$array2 = ["d", "e", "f"];
// Merge arrays
$merged = array_merge($array1, $array2);
// Split array into chunks
$chunks = array_chunk($merged, 2);
// Extract slice of array
$slice = array_slice($merged, 1, 3);

$students = [
"Alice" => ["Math" => 85, "Science" => 92, "English" => 78],
"Bob" => ["Math" => 76, "Science" => 84, "English" => 88],
"Charlie" => ["Math" => 93, "Science" => 89, "English" => 95]
];
// Calculate average grade for each student
foreach ($students as $name => $grades) {
$average = array_sum($grades) / count($grades);
echo "$name's average: " . round($average, 2) . "<br>";
}
// Find highest grade in Math
$mathGrades = array_column($students, 'Math');
$highestMath = max($mathGrades);
echo "Highest Math grade: $highestMath<br>";

$cart = [
"laptop" => ["price" => 800, "quantity" => 1],
"mouse" => ["price" => 25, "quantity" => 2],
"keyboard" => ["price" => 50, "quantity" => 1]
];
// Calculate total cost
$total = 0;
foreach ($cart as $item => $details) {
$itemTotal = $details["price"] * $details["quantity"];
$total += $itemTotal;
echo "$item: $" . $itemTotal . "<br>";
}
echo "Total: $" . $total . "<br>";

$employees = [
["name" => "John", "department" => "IT", "salary" => 50000],
["name" => "Jane", "department" => "HR", "salary" => 45000],
["name" => "Bob", "department" => "IT", "salary" => 55000],
["name" => "Alice", "department" => "Finance", "salary" => 48000]
];
// Group employees by department
$byDepartment = [];
foreach ($employees as $employee) {
$dept = $employee["department"];
$byDepartment[$dept][] = $employee;
}
// Calculate average salary by department
foreach ($byDepartment as $dept => $deptEmployees) {
$salaries = array_column($deptEmployees, 'salary');
$avgSalary = array_sum($salaries) / count($salaries);
echo "$dept average salary: $" . number_format($avgSalary) . "<br>";
}