PHP Arrays — Indexed, Associative & Multidimensional Mastery
PHP arrays are ordered hash maps that combine the features of indexed lists and key-value dictionaries — they’re the most versatile data structure in the language, functioning as lists, maps, stacks, queues, and sets.
What You’ll Learn
By the end of this tutorial, you’ll create and manipulate indexed, associative, and multidimensional arrays, use PHP’s extensive array function library, and efficiently sort and transform data.
Why Arrays Matter
Arrays are everywhere in real applications. Durga Antivirus Pro uses arrays to store threat signatures, scan results, and configuration settings. Doda Browser uses arrays for bookmarks, browsing history, and tab management. DodaZIP uses arrays to track file lists, compression metadata, and extraction paths. Without arrays, you’d have dozens of separate variables — arrays let you organize related data under one name.
Arrays Learning Path
flowchart LR
A[Control Flow] --> B[Functions]
B --> C[Arrays]
C --> D[Forms]
D --> E[Advanced OOP]
C --> F{You Are Here}
style F fill:#f90,color:#fff
What Is an Array? (The “Why” First)
Think of an array like a mailbox cluster in an apartment building. Each mailbox has a number (index) or a name (key), and you put mail (data) inside. You can check what’s in mailbox #0, add a new mailbox, or remove one.
Indexed Arrays — Numbered Mailboxes
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Apple — first item, index 0
echo $fruits[1]; // Banana
echo $fruits[2]; // Cherry
// Add a new item at the end
$fruits[] = "Date";
echo count($fruits); // 4
?>
Indexed arrays use numbers starting at 0. Think of them like a numbered list: position 0, position 1, position 2.
Associative Arrays — Named Mailboxes
<?php
$user = [
"name" => "Alice",
"age" => 30,
"city" => "Paris",
];
echo $user["name"]; // Alice
// Add new key
$user["email"] = "alice@example.com";
// Remove
unset($user["age"]);
?>
Associative arrays use named keys instead of numbers. This is useful when you want to describe your data — “this value is the name, this is the age.”
Multidimensional Arrays — Arrays Within Arrays
<?php
$users = [
[
"id" => 1,
"name" => "Alice",
"skills" => ["PHP", "MySQL", "JS"],
],
[
"id" => 2,
"name" => "Bob",
"skills" => ["Python", "Django"],
],
];
echo $users[0]["skills"][1]; // MySQL
?>
Think of this as a spreadsheet with headers. The outer array is each row, and the inner array is the columns in that row.
Essential Array Operations
Adding & Removing
<?php
$items = ["a", "b", "c"];
array_push($items, "d"); // Add to end: ["a", "b", "c", "d"]
$items[] = "e"; // Same, faster for single item
$last = array_pop($items); // Remove from end: "e"
$first = array_shift($items); // Remove from front: "a"
array_unshift($items, "z"); // Add to front: ["z", "b", "c"]
?>
Transforming with map/filter/reduce
<?php
$numbers = [1, 2, 3, 4, 5];
// array_map — transform each element
$doubled = array_map(fn($n) => $n * 2, $numbers);
// [2, 4, 6, 8, 10]
// array_filter — keep elements matching condition
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
// [2, 4] (preserves keys)
// array_reduce — combine into single value
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
// 15
?>
These are the “big three” functional operations. They replace loops with cleaner, declarative code.
Sorting — Getting Things in Order
<?php
$numbers = [3, 1, 4, 1, 5, 9, 2];
sort($numbers); // [1, 1, 2, 3, 4, 5, 9] — reindexes
$ages = ["Alice" => 30, "Bob" => 25, "Charlie" => 35];
asort($ages); // Sorts by value, keeps keys: Bob, Alice, Charlie
ksort($ages); // Sorts by key: Alice, Bob, Charlie
?>
The naming is logical: sort for indexed arrays, a+sort for associative (keeps associations), k+sort by keys.
Common Mistakes
1. Forgetting Arrays Start at 0
$arr = ["a", "b", "c"];
echo $arr[1]; // b — beginners often expect "a" here
2. isset vs array_key_exists
$arr = ["name" => null];
var_dump(isset($arr["name"])); // false (null)
var_dump(array_key_exists("name", $arr)); // true (key exists)
isset returns false for null values. array_key_exists checks if the key is defined regardless of value.
3. Modifying an Array While Iterating
foreach ($items as $key => $value) {
unset($items[$key]); // Can corrupt iteration
}4. Loose Type in array_search/in_array
$arr = ["1", 2, 3];
var_dump(in_array(1, $arr, true)); // false — strict mode
5. Confusing array_merge with + Operator
array_merge reindexes numeric keys. The + operator keeps the left array’s keys and ignores duplicates from the right.
Practice Questions
1. What’s the output of [1, 2, 3][1]?
2. Arrays are 0-indexed, so index 1 is the second element.
2. How do you check if a key exists in an associative array when the value might be null?
Use array_key_exists("key", $array). isset() returns false for null values.
3. What’s the difference between sort and asort?
sort reindexes numeric keys after sorting values. asort preserves key-value associations.
4. How do you remove duplicates from an array?
array_unique($array). For multidimensional arrays: array_unique($array, SORT_REGULAR).
5. Challenge: Write a function that groups an array of products by category.
<?php
$products = [
["name" => "Laptop", "category" => "Electronics"],
["name" => "Shirt", "category" => "Clothing"],
["name" => "Mouse", "category" => "Electronics"],
];
$grouped = [];
foreach ($products as $product) {
$grouped[$product["category"]][] = $product["name"];
}
print_r($grouped);
?>
FAQ
Try It Yourself
Create a shopping cart calculator:
<?php
$products = [
1 => ["name" => "Laptop", "price" => 999.99],
2 => ["name" => "Mouse", "price" => 24.99],
3 => ["name" => "Keyboard", "price" => 79.99],
];
$cart = [1 => 2, 3 => 1]; // 2 laptops, 1 keyboard
$total = 0;
foreach ($cart as $productId => $quantity) {
$total += $products[$productId]["price"] * $quantity;
}
echo "Total: $" . number_format($total, 2);
?>
Run with php cart.php.
What’s Next
| Lesson | Description |
|---|---|
| https://tutorials.dodatech.com/backend/php/php-forms/ | Process form data in arrays |
| https://tutorials.dodatech.com/backend/php/php-advanced/ | OOP and database with arrays |
| https://tutorials.dodatech.com/backend/php/php-functions/ | Using arrays with functions |
| MySQL | Database result sets as arrays |
| Laravel | Collections — Laravel’s enhanced arrays |
What’s Next
Congratulations on completing this Php Arrays tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro