Lesson 7 โข Intermediate
Arrays & Collections ๐ฆ
Master PHP's most powerful data structure โ indexed arrays, associative arrays, multidimensional arrays, and 30+ built-in array functions.
What You'll Learn in This Lesson
- โข Indexed arrays for ordered lists of values
- โข Associative arrays with string keys (key => value)
- โข Multidimensional arrays for complex data structures
- โข Sorting, searching, filtering, and transforming arrays
- โข array_map, array_filter, array_reduce for functional programming
1๏ธโฃ Three Types of PHP Arrays
| Type | Syntax | Use Case |
|---|---|---|
| Indexed | ["a", "b", "c"] | Ordered lists |
| Associative | ["name" => "Alice"] | Key-value data |
| Multidimensional | [["a", 1], ["b", 2]] | Tables, nested data |
Try It: Array Types
Create indexed, associative, and multidimensional arrays and access their elements
// PHP Arrays & Collections (simulated in JavaScript)
console.log("=== Indexed Arrays ===");
console.log();
// PHP: $fruits = ["Apple", "Banana", "Cherry", "Date"];
let fruits = ["Apple", "Banana", "Cherry", "Date"];
console.log("Fruits array: [" + fruits.join(", ") + "]");
console.log("First: $fruits[0] = " + fruits[0]);
console.log("Last: $fruits[3] = " + fruits[3]);
console.log("Count: count($fruits) = " + fruits.length);
console.log();
// Adding elements
fruits.push("Elderberry"); /
...Try It: Array Functions
Sort, search, filter, map, reduce, merge, and slice arrays
// PHP Array Functions (simulated in JavaScript)
console.log("=== Sorting Arrays ===");
console.log();
let numbers = [5, 2, 8, 1, 9, 3, 7];
console.log("Original: [" + numbers.join(", ") + "]");
// sort() โ sorts ascending
let sorted = [...numbers].sort((a, b) => a - b);
console.log("sort(): [" + sorted.join(", ") + "]");
// rsort() โ sorts descending
let rsorted = [...numbers].sort((a, b) => b - a);
console.log("rsort(): [" + rsorted.join(", ") + "]");
console.log();
console.log("=== Sea
...โ ๏ธ Common Mistakes
[0 => "a", "name" => "b"] is valid but confusing. Pick one style per array.sort() re-indexes keys! Use asort() to preserve key-value associations.array_map() or array_filter() instead.array_map(), array_filter(), and array_reduce() for clean, functional-style code. They're faster and safer than manual loops.๐ Quick Reference โ PHP Arrays
| Function | Purpose | Returns |
|---|---|---|
| count() | Array length | int |
| in_array() | Check if value exists | bool |
| array_map() | Transform each element | array |
| array_filter() | Keep matching elements | array |
| array_merge() | Combine arrays | array |
| sort() / asort() | Sort values | void (modifies) |
๐ Lesson Complete!
You've mastered PHP arrays! Next, learn how to read and write files on the server.
Sign up for free to track which lessons you've completed and get learning reminders.