An array in PHP is an ordered map that associates values to keys. Unlike arrays in C or Java, PHP arrays can hold different data types simultaneously and act as lists, hash tables, dictionaries, queues, and stacks.
0.flowchart TD
A["PHP Array Types"] --> B["Indexed Array"]
A --> C["Associative Array"]
A --> D["Multidimensional Array"]
B --> B1["['Apple', 'Banana', 'Cherry']"]
C --> C1="['name' => 'Alice', 'role' => 'Admin']"
D --> D1="[['id' => 1, 'title' => 'A'], ['id' => 2, 'title' => 'B']]"
count($arr): Returns total element count.array_push($arr, $val) or $arr[] = $val: Appends element to end.array_merge($arr1, $arr2) or [...$arr1, ...$arr2]: Combines arrays.array_filter($arr, callback): Filters elements based on truthy condition.array_map(callback, $arr): Transforms each element in array.<?php
declare(strict_types=1);
// 1. Multidimensional Associative Array
$products = [
['id' => 101, 'name' => 'Mechanical Keyboard', 'price' => 120.00, 'category' => 'Hardware'],
['id' => 102, 'name' => 'Ergonomic Mouse', 'price' => 45.50, 'category' => 'Hardware'],
['id' => 103, 'name' => 'Developer PDF Ebook', 'price' => 15.00, 'category' => 'Digital'],
];
// 2. Filter Products (Price > $20) using array_filter
$premiumProducts = array_filter($products, fn(array $item): bool => $item['price'] > 20.0);
// 3. Extract Array Column (Product Names)
$productNames = array_column($premiumProducts, 'name');
// 4. Spread Operator Array Merging (...)
$additionalItems = ['Monitor Stand', 'USB-C Hub'];
$fullInventory = [...$productNames, ...$additionalItems];
echo "Premium Products Count: " . count($premiumProducts) . "
";
echo "Full Inventory List: " . implode(" | ", $fullInventory) . "
";
[]: Prefer [$a, $b] over legacy array($a, $b).array_column() for Nested Collection Operations: Easily extract specific fields from tabular array records.[...] for Merging: Faster and cleaner than array_merge().Given $users = [['name' => 'John', 'age' => 20], ['name' => 'Jane', 'age' => 30]], write code using array_column() to extract an array of names!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.