Skip to content

PHP Arrays

Arrays store multiple values in a single variable. PHP supports three types: indexed (numeric keys), associative (named keys), and multidimensional (arrays within arrays).


The simplest array type. An ordered list where each value has a numeric index starting at 0.

// Short syntax (recommended)
$fruits = ["apple", "banana", "orange"];
// Or using array()
$fruits = array("apple", "banana", "orange");

Access elements by their index:

$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Red
echo $colors[2]; // Blue
// Modify an element
$colors[1] = "Yellow";
// Add to the end
$colors[] = "Purple";

Associative arrays use string keys instead of numeric indices. PHP’s superglobals like $_POST and $_GET work this way.

$person = [
"name" => "John Doe",
"age" => 30,
"city" => "New York"
];

Access elements by their key:

$user = [
"firstName" => "John",
"lastName" => "Doe",
"email" => "john@example.com"
];
echo $user["email"]; // john@example.com
// Modify a value
$user["email"] = "j.doe@newdomain.com";
// Add a new key-value pair
$user["city"] = "New York";

Arrays can contain other arrays, which is useful for representing structured data like database rows or nested configurations.

// 2D indexed array
$students = [
["John", 85, "Math"],
["Jane", 92, "Science"],
["Bob", 78, "History"]
];
// Nested associative array
$products = [
"laptop" => [
"brand" => "Dell",
"price" => 800,
"specs" => ["RAM" => "8GB", "Storage" => "256GB"]
],
"phone" => [
"brand" => "iPhone",
"price" => 999
]
];

Access nested elements by chaining brackets:

echo $students[0][0]; // John
echo $products["laptop"]["brand"]; // Dell
echo $products["laptop"]["specs"]["RAM"]; // 8GB

$fruits = ["apple", "banana"];
$fruits[] = "orange"; // Add to end
array_push($fruits, "grape", "mango"); // Add multiple to end
array_unshift($fruits, "strawberry"); // Add to beginning
$fruits = ["apple", "banana", "orange", "grape"];
array_pop($fruits); // Remove last element
array_shift($fruits); // Remove first element
unset($fruits[1]); // Remove by index
// Remove by value
$key = array_search("orange", $fruits);
if ($key !== false) {
unset($fruits[$key]);
}

The foreach loop is the most common way to iterate over arrays.

// Indexed array - just values
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color . "\n";
}
// Associative array - keys and values
$user = ["name" => "John", "email" => "john@example.com"];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}

For indexed arrays where you need the index, a for loop works well:

$numbers = [10, 20, 30];
for ($i = 0; $i < count($numbers); $i++) {
echo "Index $i: " . $numbers[$i] . "\n";
}

$fruits = ["apple", "banana", "orange"];
count($fruits); // 3
empty($fruits); // false
in_array("apple", $fruits); // true
array_key_exists("name", $person); // true/false
array_search("banana", $fruits); // 1 (the index)
$numbers = [3, 1, 4, 1, 5];
sort($numbers); // Sort ascending
rsort($numbers); // Sort descending
array_reverse($numbers); // Reverse order
array_unique($numbers); // Remove duplicates
// Filter elements
$evens = array_filter($numbers, fn($n) => $n % 2 == 0);
// Transform each element
$doubled = array_map(fn($n) => $n * 2, $numbers);
$a = ["a", "b"];
$b = ["c", "d"];
array_merge($a, $b); // ["a", "b", "c", "d"]
array_chunk($a, 2); // Split into chunks of 2
array_slice($a, 1, 2); // Extract portion

$cart = [
"laptop" => ["price" => 800, "qty" => 1],
"mouse" => ["price" => 25, "qty" => 2],
"keyboard" => ["price" => 50, "qty" => 1]
];
$total = 0;
foreach ($cart as $item => $details) {
$subtotal = $details["price"] * $details["qty"];
$total += $subtotal;
echo "$item: \$$subtotal\n";
}
echo "Total: \$$total";

Before accessing an array element, check that the key exists to avoid errors:

if (isset($person["email"])) {
echo $person["email"];
}

Use type hints in functions that expect arrays:

function calculateTotal(array $prices): float {
return array_sum($prices);
}