Session 3.4 – PHP Arrays and Array Functions

Module 3: PHP Basics | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Understand what arrays are and why they are useful
  • Create and manipulate indexed arrays
  • Work with associative arrays (key-value pairs)
  • Create and access multidimensional arrays
  • Use various array functions for manipulation
  • Sort arrays using different sorting functions
  • Apply arrays to solve real-world problems

Introduction to Arrays

What is an Array?

An array is a special variable that can hold multiple values at once. Instead of creating separate variables for related data, you can store them all in a single array.

Without Arrays
$fruit1 = "Apple";
$fruit2 = "Banana";
$fruit3 = "Orange";
$fruit4 = "Mango";
With Arrays
$fruits = [
    "Apple",
    "Banana",
    "Orange",
    "Mango"
];

Types of Arrays in PHP

Indexed Arrays

Arrays with numeric indices

Associative Arrays

Arrays with named keys

Multidimensional

Arrays containing other arrays

Indexed Arrays

Indexed arrays use numeric indices (starting from 0) to access elements.

Creating Indexed Arrays

<?phplt;?phplt;?php
    // Method 1: Using array() function
    $colors = array("Red", "Green", "Blue");

    // Method 2: Using short syntax (PHP 5.4+)
    $fruits = ["Apple", "Banana", "Orange"];

    // Method 3: Creating empty array and adding elements
    $numbers = [];
    $numbers[0] = 10;
    $numbers[1] = 20;
    $numbers[2] = 30;

    // Method 4: Adding elements without specifying index
    $animals = [];
    $animals[] = "Dog";    // Index 0
    $animals[] = "Cat";    // Index 1
    $animals[] = "Bird";   // Index 2
?>

Accessing Array Elements

<?phplt;?phplt;?php
    $fruits = ["Apple", "Banana", "Orange", "Mango"];

    echo $fruits[0];  // Apple
    echo $fruits[1];  // Banana
    echo $fruits[2];  // Orange

    // Get array length
    $length = count($fruits);
    echo "Array has $length elements";  // Array has 4 elements

    // Modify array element
    $fruits[1] = "Strawberry";
    echo $fruits[1];  // Strawberry
?>

Displaying Arrays

<?phplt;?phplt;?php
    $numbers = [1, 2, 3, 4, 5];

    // Using print_r() - readable format
    print_r($numbers);
    // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

    // Using var_dump() - detailed information
    var_dump($numbers);
    // Output: array(5) { [0]=> int(1) [1]=> int(2) ... }

    // Pretty print for debugging
    echo "<pre>";
    print_r($numbers);
    echo "</pre>";
?>

Associative Arrays

Associative arrays use named keys (strings) instead of numeric indices.

Creating Associative Arrays

<?phplt;?phplt;?php
    // Student information
    $student = [
        "name" => "John Doe",
        "age" => 20,
        "grade" => "A",
        "gpa" => 3.8,
        "email" => "john@example.com"
    ];

    // Country capitals
    $capitals = [
        "USA" => "Washington D.C.",
        "UK" => "London",
        "France" => "Paris",
        "Japan" => "Tokyo"
    ];

    // Product details
    $product = [
        "id" => 101,
        "name" => "Laptop",
        "price" => 999.99,
        "inStock" => true
    ];
?>

Accessing Associative Array Elements

<?phplt;?phplt;?php
    $student = [
        "name" => "John Doe",
        "age" => 20,
        "grade" => "A"
    ];

    // Access elements using keys
    echo $student["name"];   // John Doe
    echo $student["age"];    // 20
    echo $student["grade"];  // A

    // Modify value
    $student["age"] = 21;

    // Add new key-value pair
    $student["gpa"] = 3.8;

    // Loop through associative array
    foreach ($student as $key => $value) {
        echo $key . ": " . $value . "<br>";
    }
?>
Output:
name: John Doe
age: 21
grade: A
gpa: 3.8

Multidimensional Arrays

Multidimensional arrays contain one or more arrays within them.

Two-Dimensional Arrays

<?phplt;?phplt;?php
    // Array of students
    $students = [
        ["John", 20, "A"],
        ["Jane", 22, "B"],
        ["Bob", 21, "A"]
    ];

    // Access elements
    echo $students[0][0];  // John
    echo $students[0][1];  // 20
    echo $students[1][0];  // Jane

    // Associative multidimensional array
    $users = [
        [
            "name" => "Alice",
            "email" => "alice@example.com",
            "age" => 25
        ],
        [
            "name" => "Bob",
            "email" => "bob@example.com",
            "age" => 30
        ]
    ];

    echo $users[0]["name"];   // Alice
    echo $users[1]["email"];  // bob@example.com
?>

Looping Through Multidimensional Arrays

<?phplt;?phplt;?php
    $products = [
        ["name" => "Laptop", "price" => 999, "qty" => 5],
        ["name" => "Mouse", "price" => 29, "qty" => 15],
        ["name" => "Keyboard", "price" => 79, "qty" => 10]
    ];

    foreach ($products as $product) {
        echo "Product: " . $product["name"] . "<br>";
        echo "Price: $" . $product["price"] . "<br>";
        echo "Quantity: " . $product["qty"] . "<br><br>";
    }
?>

Array Traversal Methods

Using foreach Loop

<?phplt;?phplt;?php
    $fruits = ["Apple", "Banana", "Orange"];

    foreach ($fruits as $fruit) {
        echo $fruit . "<br>";
    }
?>

Using for Loop

<?phplt;?phplt;?php
    $numbers = [10, 20, 30, 40, 50];

    for ($i = 0; $i < count($numbers); $i++) {
        echo $numbers[$i] . "<br>";
    }
?>

Using array_map()

<?phplt;?phplt;?php
    $numbers = [1, 2, 3, 4, 5];

    // Double each number
    $doubled = array_map(function($n) {
        return $n * 2;
    }, $numbers);

    print_r($doubled);  // Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )
?>

Common Array Functions

count() / sizeof()

Returns the number of elements in an array

$arr = [1, 2, 3, 4, 5];
echo count($arr); // 5
array_push()

Adds one or more elements to the end

$arr = [1, 2, 3];
array_push($arr, 4, 5);
// [1, 2, 3, 4, 5]
array_pop()

Removes and returns the last element

$arr = [1, 2, 3];
$last = array_pop($arr);
// $last = 3, $arr = [1, 2]
array_shift()

Removes and returns the first element

$arr = [1, 2, 3];
$first = array_shift($arr);
// $first = 1, $arr = [2, 3]
array_unshift()

Adds elements to the beginning

$arr = [2, 3];
array_unshift($arr, 1);
// [1, 2, 3]
in_array()

Checks if a value exists in array

$arr = ["a", "b", "c"];
if (in_array("b", $arr)) {
    echo "Found!";
}
array_merge()

Merges two or more arrays

$arr1 = [1, 2];
$arr2 = [3, 4];
$merged = array_merge($arr1, $arr2);
// [1, 2, 3, 4]
array_slice()

Extracts a portion of an array

$arr = [1, 2, 3, 4, 5];
$slice = array_slice($arr, 1, 3);
// [2, 3, 4]
array_keys()

Returns all keys from an array

$arr = ["a" => 1, "b" => 2];
$keys = array_keys($arr);
// ["a", "b"]
array_values()

Returns all values from an array

$arr = ["a" => 1, "b" => 2];
$values = array_values($arr);
// [1, 2]

Sorting Arrays

PHP provides various functions to sort arrays in different ways:

Function Description Example
sort() Sort indexed array (ascending) sort($arr);
rsort() Sort indexed array (descending) rsort($arr);
asort() Sort associative array by value asort($arr);
arsort() Sort associative array by value (descending) arsort($arr);
ksort() Sort associative array by key ksort($arr);
krsort() Sort associative array by key (descending) krsort($arr);

Sorting Examples

<?phplt;?phplt;?php
    // Sort indexed array
    $numbers = [5, 2, 8, 1, 9];
    sort($numbers);
    print_r($numbers);  // [1, 2, 5, 8, 9]

    // Sort in descending order
    $scores = [85, 92, 78, 95, 88];
    rsort($scores);
    print_r($scores);  // [95, 92, 88, 85, 78]

    // Sort associative array by value
    $ages = ["John" => 25, "Jane" => 22, "Bob" => 30];
    asort($ages);
    print_r($ages);  // ["Jane" => 22, "John" => 25, "Bob" => 30]

    // Sort by key
    $grades = ["C" => 78, "A" => 95, "B" => 88];
    ksort($grades);
    print_r($grades);  // ["A" => 95, "B" => 88, "C" => 78]
?>

Practical Examples

Example 1: Shopping Cart

<?phplt;?phplt;?php
    $cart = [
        ["product" => "Laptop", "price" => 999, "qty" => 1],
        ["product" => "Mouse", "price" => 29, "qty" => 2],
        ["product" => "Keyboard", "price" => 79, "qty" => 1]
    ];

    $total = 0;
    echo "<h3>Shopping Cart</h3>";
    foreach ($cart as $item) {
        $subtotal = $item["price"] * $item["qty"];
        echo $item["product"] . ": $" . $item["price"] .
             " x " . $item["qty"] . " = $" . $subtotal . "<br>";
        $total += $subtotal;
    }
    echo "<strong>Total: $" . $total . "</strong>";
?>

Example 2: Grade Calculator

<?phplt;?phplt;?php
    $scores = [85, 92, 78, 95, 88, 76, 90];

    $total = array_sum($scores);
    $count = count($scores);
    $average = $total / $count;

    $highest = max($scores);
    $lowest = min($scores);

    echo "Total Scores: " . count($scores) . "<br>";
    echo "Average: " . round($average, 2) . "<br>";
    echo "Highest: " . $highest . "<br>";
    echo "Lowest: " . $lowest;
?>

Example 3: Remove Duplicates

<?phplt;?phplt;?php
    $numbers = [1, 2, 3, 2, 4, 1, 5, 3, 6];

    echo "Original: ";
    print_r($numbers);

    $unique = array_unique($numbers);
    echo "<br>Unique: ";
    print_r($unique);
    // Output: [1, 2, 3, 4, 5, 6]
?>

Session Summary

Key Points
  • Arrays store multiple values in a single variable
  • Indexed arrays use numeric indices starting from 0
  • Associative arrays use named keys to identify elements
  • Multidimensional arrays contain other arrays as elements
  • Use count() to get array length
  • Common array functions: push, pop, shift, unshift, merge, slice
  • Sort arrays using sort(), rsort(), asort(), ksort() functions
  • Use foreach loop for easy array iteration
  • Arrays are essential for managing collections of related data
Next Session Preview

In the next session, we will set up the XAMPP environment and learn how to configure a local web server for PHP development.