PHP Arrays
What are Arrays?
Section titled “What are Arrays?”Arrays store multiple values in a single variable. PHP supports three types: indexed (numeric keys), associative (named keys), and multidimensional (arrays within arrays).
Indexed Arrays
Section titled “Indexed 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]; // Redecho $colors[2]; // Blue
// Modify an element$colors[1] = "Yellow";
// Add to the end$colors[] = "Purple";Associative Arrays
Section titled “Associative Arrays”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";Multidimensional Arrays
Section titled “Multidimensional Arrays”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]; // Johnecho $products["laptop"]["brand"]; // Dellecho $products["laptop"]["specs"]["RAM"]; // 8GBModifying Arrays
Section titled “Modifying Arrays”Adding Elements
Section titled “Adding Elements”$fruits = ["apple", "banana"];
$fruits[] = "orange"; // Add to endarray_push($fruits, "grape", "mango"); // Add multiple to endarray_unshift($fruits, "strawberry"); // Add to beginningRemoving Elements
Section titled “Removing Elements”$fruits = ["apple", "banana", "orange", "grape"];
array_pop($fruits); // Remove last elementarray_shift($fruits); // Remove first elementunset($fruits[1]); // Remove by index
// Remove by value$key = array_search("orange", $fruits);if ($key !== false) { unset($fruits[$key]);}Looping Through Arrays
Section titled “Looping Through Arrays”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";}Common Array Functions
Section titled “Common Array Functions”Getting Information
Section titled “Getting Information”$fruits = ["apple", "banana", "orange"];
count($fruits); // 3empty($fruits); // falsein_array("apple", $fruits); // truearray_key_exists("name", $person); // true/falsearray_search("banana", $fruits); // 1 (the index)Transforming Arrays
Section titled “Transforming Arrays”$numbers = [3, 1, 4, 1, 5];
sort($numbers); // Sort ascendingrsort($numbers); // Sort descendingarray_reverse($numbers); // Reverse orderarray_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);Combining Arrays
Section titled “Combining Arrays”$a = ["a", "b"];$b = ["c", "d"];
array_merge($a, $b); // ["a", "b", "c", "d"]array_chunk($a, 2); // Split into chunks of 2array_slice($a, 1, 2); // Extract portionPractical Example: Shopping Cart
Section titled “Practical Example: Shopping Cart”$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);}