PHP Arrays
What are Arrays?
Section titled “What are Arrays?”Arrays are a collection of elements that are stored in a single variable. PHP supports several types of arrays that allow you to store multiple values in an organized way.
Types of Arrays in PHP
Section titled “Types of Arrays in PHP”PHP supports three main types of arrays, each serving a different purpose.
- Indexed Arrays: Arrays with numeric keys.
- Associative Arrays: Arrays with named keys (key-value pairs).
- Multidimensional Arrays: Arrays containing other arrays.
1. Indexed Arrays
Section titled “1. Indexed Arrays”This is the simplest type of array. It’s an ordered list where each value is identified by a numeric index, which starts at 0.
Creating Indexed Arrays: Syntax
Section titled “Creating Indexed Arrays: Syntax”You can use the modern short array syntax [] (recommended) or the older array() constructor.
// Method 1: Using array() function$fruits = array("apple", "banana", "orange");
// Method 2: Using short array syntax (PHP 5.4+)$fruits = ["apple", "banana", "orange"];
// Method 3: Manual assignment$fruits[0] = "apple";$fruits[1] = "banana";$fruits[2] = "orange";Accessing Elements:
Section titled “Accessing Elements:”You access an element by referring to its index number inside square brackets [].
<?php$colors = ["Red", "Green", "Blue"];
// Remember, the index starts at 0!echo $colors[0]; // Outputs: Redecho "<br>";echo $colors[2]; // Outputs: Blue
// You can also modify an element$colors[1] = "Yellow";echo "<br>";echo $colors[1]; // Outputs: Yellow
// To add a new element to the end of the array$colors[] = "Purple";// The $colors array is now ["Red", "Yellow", "Blue", "Purple"]?>2. Associative Arrays
Section titled “2. Associative Arrays”- Associative arrays use named keys instead of numeric indices.
- They are the foundation of how PHP handles form data ($_POST,$_GET) and much more.
- Instead of using numeric indexes, you assign a custom key (a string) to each value.
Creating Associative Arrays: Syntax
Section titled “Creating Associative Arrays: Syntax”The syntax uses => to associate a key with a value.
// Method 1: Using array() function$person = array(    "name" => "John Doe",    "age" => 30,    "city" => "New York");
// Method 2: Using short array syntax (PHP 5.4+)$person = [    "name" => "John Doe",    "age" => 30,    "city" => "New York"];
// Method 3: Manual assignment$person["name"] = "John Doe";$person["age"] = 30;$person["city"] = "New York";Accessing Associative Array Elements
Section titled “Accessing Associative Array Elements”You access elements using their unique string keys.
<?php$user = [    "firstName" => "John",    "lastName"  => "Doe",    "email"     => "john.doe@example.com"];
echo "User's email is: " . $user["email"]; // Outputs: User's email is: john.doe@example.com
// Modifying a value$user["email"] = "j.doe@newdomain.com";
// Adding a new key-value pair$user["city"] = "New York";?>Best Practices for Arrays
Section titled “Best Practices for Arrays”// Good practice: Type hintingfunction processNumbers(array $numbers): array {    return array_map(function($n) {        return $n * 2;    }, $numbers);}
// Good practice: Check if key existsif (isset($person["email"])) {    echo $person["email"];} else {    echo "Email not provided";}3. Multidimensional Arrays
Section titled “3. Multidimensional Arrays”A multidimensional array is an array that contains one or more other arrays. This is perfect for representing complex data structures like a list of products where each product has its own properties, or rows of data from a database table.
Creating Multidimensional Arrays: Syntax
Section titled “Creating Multidimensional Arrays: Syntax”// 2D Array$students = [    ["John", 85, "Math"],    ["Jane", 92, "Science"],    ["Bob", 78, "History"]];
// Associative multidimensional array$products = [    "laptop" => [        "brand" => "Dell",        "price" => 800,        "specs" => ["RAM" => "8GB", "Storage" => "256GB SSD"]    ],    "phone" => [        "brand" => "iPhone",        "price" => 999,        "specs" => ["RAM" => "6GB", "Storage" => "128GB"]    ]];Accessing Elements:
Section titled “Accessing Elements:”// Accessing 2D arrayecho $students[0][0]; // Output: Johnecho $students[1][2]; // Output: Science
// Accessing associative multidimensional arrayecho $products["laptop"]["brand"]; // Output: Dellecho $products["phone"]["specs"]["RAM"]; // Output: 6GBCommon Array Operations
Section titled “Common Array Operations”Adding Elements
Section titled “Adding Elements”$fruits = ["apple", "banana"];
// Add to end$fruits[] = "orange";array_push($fruits, "grape", "mango");
// Add to beginningarray_unshift($fruits, "strawberry");
// Add at specific index (associative)$fruits["tropical"] = "pineapple";Removing Elements
Section titled “Removing Elements”$fruits = ["apple", "banana", "orange", "grape"];
// Remove last element$lastFruit = array_pop($fruits);
// Remove first element$firstFruit = array_shift($fruits);
// Remove specific element by keyunset($fruits[1]);
// Remove specific value$key = array_search("orange", $fruits);if ($key !== false) {    unset($fruits[$key]);}Looping Through Arrays
Section titled “Looping Through Arrays”For Loop (Indexed Arrays):
Section titled “For Loop (Indexed Arrays):”$numbers = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($numbers); $i++) {    echo $numbers[$i] . " ";}Foreach Loop:
Section titled “Foreach Loop:”The most common task you’ll perform with an array is to loop through it and do something with each element. The foreach loop is designed specifically for this.
<?php// Looping through an indexed array$colors = ["Red", "Green", "Blue"];
echo "<ul>";foreach ($colors as $color) {    echo "<li>" . $color . "</li>";}echo "</ul>";
// Looping through an associative array to get both key and value$user = [    "First Name" => "John",    "Last Name"  => "Doe",    "Email"      => "john.doe@example.com"];
echo "<h3>User Details</h3>";foreach ($user as $key => $value) {    echo "<strong>" . $key . ":</strong> " . $value . "<br>";}?>While Loop:
Section titled “While Loop:”$fruits = ["apple", "banana", "orange"];$i = 0;
while ($i < count($fruits)) {    echo $fruits[$i] . " ";    $i++;}Useful Array Functions
Section titled “Useful Array Functions”Array Information
Section titled “Array Information”$fruits = ["apple", "banana", "orange"];
// Get array length$length = count($fruits); // 3
// Check if array is empty$isEmpty = empty($fruits); // false
// Check if key exists$keyExists = array_key_exists("name", $person); // true/false
// Check if value exists$valueExists = in_array("apple", $fruits); // trueArray Manipulation
Section titled “Array Manipulation”$numbers = [3, 1, 4, 1, 5, 9];
// Sort arraysort($numbers); // [1, 1, 3, 4, 5, 9]
// Reverse array$reversed = array_reverse($numbers);
// Get unique values$unique = array_unique($numbers);
// Filter array$evenNumbers = array_filter($numbers, function($n) {    return $n % 2 == 0;});
// Map array (transform each element)$doubled = array_map(function($n) {    return $n * 2;}, $numbers);Array Merging and Splitting
Section titled “Array Merging and Splitting”$array1 = ["a", "b", "c"];$array2 = ["d", "e", "f"];
// Merge arrays$merged = array_merge($array1, $array2);
// Split array into chunks$chunks = array_chunk($merged, 2);
// Extract slice of array$slice = array_slice($merged, 1, 3);Practical Examples
Section titled “Practical Examples”Example 1: Student Grade Management
Section titled “Example 1: Student Grade Management”$students = [    "Alice" => ["Math" => 85, "Science" => 92, "English" => 78],    "Bob" => ["Math" => 76, "Science" => 84, "English" => 88],    "Charlie" => ["Math" => 93, "Science" => 89, "English" => 95]];
// Calculate average grade for each studentforeach ($students as $name => $grades) {    $average = array_sum($grades) / count($grades);    echo "$name's average: " . round($average, 2) . "<br>";}
// Find highest grade in Math$mathGrades = array_column($students, 'Math');$highestMath = max($mathGrades);echo "Highest Math grade: $highestMath<br>";Example 2: Shopping Cart
Section titled “Example 2: Shopping Cart”$cart = [    "laptop" => ["price" => 800, "quantity" => 1],    "mouse" => ["price" => 25, "quantity" => 2],    "keyboard" => ["price" => 50, "quantity" => 1]];
// Calculate total cost$total = 0;foreach ($cart as $item => $details) {    $itemTotal = $details["price"] * $details["quantity"];    $total += $itemTotal;    echo "$item: $" . $itemTotal . "<br>";}
echo "Total: $" . $total . "<br>";Example 3: Data Processing
Section titled “Example 3: Data Processing”$employees = [    ["name" => "John", "department" => "IT", "salary" => 50000],    ["name" => "Jane", "department" => "HR", "salary" => 45000],    ["name" => "Bob", "department" => "IT", "salary" => 55000],    ["name" => "Alice", "department" => "Finance", "salary" => 48000]];
// Group employees by department$byDepartment = [];foreach ($employees as $employee) {    $dept = $employee["department"];    $byDepartment[$dept][] = $employee;}
// Calculate average salary by departmentforeach ($byDepartment as $dept => $deptEmployees) {    $salaries = array_column($deptEmployees, 'salary');    $avgSalary = array_sum($salaries) / count($salaries);    echo "$dept average salary: $" . number_format($avgSalary) . "<br>";}