Arrays are PHP's way of storing multiple values in a single variable. Think of them as a numbered list or a labeled filing cabinet. In PHP, arrays are incredibly flexible โ they can grow and shrink dynamically, and they can hold any mix of types.
Indexed Arrays
An indexed array uses numeric keys, starting at 0. It's the simplest array type โ just a list of values. You can create one with array() or the shorthand [].
<?php
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Red
echo $colors[1]; // Green
echo $colors[2]; // Blue
// Add a new element
$colors[] = "Yellow";
?>
Try it Yourself โ
Associative Arrays
Associative arrays use named keys instead of numbers. They're like dictionaries โ you look up a word (key) and get the definition (value). This is where PHP arrays really shine.
<?php
$student = [
"name" => "Bilal",
"age" => 25,
"course" => "Web Development"
];
echo $student["name"]; // Bilal
echo $student["course"]; // Web Development
?>
Multidimensional Arrays
An array inside an array. This is how you represent tables, grids, or complex data structures. Each element in the outer array is itself an array.
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[0][0]; // 1
echo $matrix[1][2]; // 6
$users = [
["name" => "Ali", "email" => "ali@test.com"],
["name" => "Sara", "email" => "sara@test.com"]
];
echo $users[1]["email"]; // sara@test.com
?>
Useful Array Functions
PHP ships with dozens of array functions. These are the ones I use most:
<?php
$items = ["Pen", "Book", "Eraser"];
echo count($items); // 3 โ number of elements
sort($items); // sorts alphabetically
print_r($items); // prints array structure
array_push($items, "Ruler"); // adds element at the end
array_pop($items); // removes last element
array_shift($items); // removes first element
$reversed = array_reverse($items);
echo in_array("Book", $items); // 1 (true) โ checks if value exists
?>