"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Sunday, September 1, 2024

Class 7: Arrays - Part 2

 

Class 7: Arrays - Part 2


Objective:

Understand multidimensional arrays and how to manipulate them.

Learn array sorting and filtering techniques.

Outcome:

Students will be able to create and work with multidimensional arrays and apply sorting and filtering functions to manage data.

1. Multidimensional Arrays

What Are Multidimensional Arrays?

A multidimensional array is an array containing one or more arrays. It allows you to store data in a structured format, similar to a table or grid. Each element in a multidimensional array can itself be an array, allowing for complex data relationships.

Example of a Two-Dimensional Array:

A two-dimensional array can be thought of as a table with rows and columns.

<?php

// Creating a two-dimensional array

$students = [

    ["John", "Math", 85],

    ["Alice", "Science", 90],

    ["Bob", "History", 78]

];

 

// Accessing elements

echo $students[0][0]; // Output: John

echo $students[1][1]; // Output: Science

echo $students[2][2]; // Output: 78

?>

 

 

 Explanation:

The $students array contains three sub-arrays, each representing a student.

Each sub-array stores the student's name, subject, and score.

You can access specific elements using two indices, like $students[0][0] to get "John".

Manipulating Multidimensional Arrays

You can modify, add, or remove elements from a multidimensional array just like you would with a single-dimensional array.

Example of Modifying Elements:

<?php

// Modifying an element in a two-dimensional array

$students[0][2] = 88; // Changing John's score from 85 to 88

// Adding a new student

$students[] = ["Charlie", "English", 82];

print_r($students); // Display the updated array

?> 

Explanation:

We changed John's score by directly accessing and modifying the element.

We added a new student to the array using the [] syntax.

2. Array Sorting Techniques

Sorting arrays is a common task when working with data. PHP provides several functions to sort arrays in different ways.

Sorting Indexed Arrays

You can sort indexed arrays in ascending or descending order using sort() and rsort() functions.

Example:

<?php

$numbers = [4, 2, 8, 6];

// Sorting in ascending order

sort($numbers);

print_r($numbers); // Output: [2, 4, 6, 8]

// Sorting in descending order

rsort($numbers);

print_r($numbers); // Output: [8, 6, 4, 2]

?>

 

 

Explanation:

sort($numbers) sorts the array in ascending order.

rsort($numbers) sorts the array in descending order.

Sorting Associative Arrays

For associative arrays, you can sort by values or keys using asort(), arsort(), ksort(), and krsort().

Example:

<?php

$ages = ["John" => 25, "Alice" => 22, "Bob" => 28];

// Sorting by value in ascending order

asort($ages);

print_r($ages); // Output: ["Alice" => 22, "John" => 25, "Bob" => 28]

// Sorting by key in ascending order

ksort($ages);

print_r($ages); // Output: ["Alice" => 22, "Bob" => 28, "John" => 25]

?>

 

 

Explanation:

asort($ages) sorts the array by values in ascending order, maintaining the key-value association.

ksort($ages) sorts the array by keys in ascending order.

3. Array Filtering Techniques

Filtering arrays allows you to select specific elements that meet certain criteria. The array_filter() function is particularly useful for this purpose.

Example:

<?php

$numbers = [1, 2, 3, 4, 5, 6];

// Filtering even numbers

$evenNumbers = array_filter($numbers, function($number) {

    return $number % 2 == 0;

});

print_r($evenNumbers); // Output: [2, 4, 6]

?>

 

 Explanation:

array_filter($numbers, function($number) {...}) filters the array by applying a custom function that returns true for even numbers.

4. Practical Example: 

Working with Multidimensional Arrays and Sorting

Task:

Create a multidimensional array to store student data (name, subject, and grade). Sort the array by students' grades in descending order and display the sorted list.

Code:

<?php

// Step 1: Create a multidimensional array to store student data

$students = [

    ["name" => "John", "subject" => "Math", "grade" => 85],

    ["name" => "Alice", "subject" => "Science", "grade" => 90],

    ["name" => "Bob", "subject" => "History", "grade" => 78]

];

 

// Step 2: Sort the array by grade in descending order

usort($students, function($a, $b) {

    return $b['grade'] <=> $a['grade'];

});

 

// Step 3: Display the sorted list of students

echo "Students sorted by grades (highest to lowest):\n";

foreach ($students as $student) {

    echo "Name: " . $student['name'] . ", Subject: " . $student['subject'] . ", Grade: " . $student['grade'] . "\n";

}

?>

 

 Explanation:

We used usort() with a custom comparison function to sort the array by grades in descending order.

The foreach loop displays each student's information after sorting.

Assignments

Assignment 1: Multidimensional Array Manipulation

Task:

Create a multidimensional array to store information about three products (name, category, and price). Update the price of one product, add a new product, and display the updated product list.

Code:

<?php

// Step 1: Create a multidimensional array for products

$products = [

    ["name" => "Laptop", "category" => "Electronics", "price" => 1000],

    ["name" => "Desk Chair", "category" => "Furniture", "price" => 150],

    ["name" => "Book", "category" => "Stationery", "price" => 10]

];

 

// Step 2: Update the price of the "Desk Chair" to 175

foreach ($products as &$product) {

    if ($product["name"] === "Desk Chair") {

        $product["price"] = 175;

    }

}

unset($product); // Unset reference to avoid issues

 

// Step 3: Add a new product

$products[] = ["name" => "Smartphone", "category" => "Electronics", "price" => 700];

 

// Step 4: Display the updated product list

echo "Updated Product List:\n";

foreach ($products as $product) {

    echo "Name: " . $product["name"] . ", Category: " . $product["category"] . ", Price: $" . $product["price"] . "\n";

}

?>

 

 Explanation:

We create a multidimensional array $products with product details.

We update the price of the "Desk Chair" by iterating through the array and checking for the product name.

We add a new product to the array using the [] syntax.

We display the updated product list using a foreach loop.

Assignment 2: 

Sorting a Multidimensional Array by Price

Task:

Create a multidimensional array of products (name, category, price). Sort the products by price in ascending order and display the sorted list.

Code:

<?php

// Step 1: Create a multidimensional array for products

$products = [

    ["name" => "Laptop", "category" => "Electronics", "price" => 1000],

    ["name" => "Desk Chair", "category" => "Furniture", "price" => 150],

    ["name" => "Book", "category" => "Stationery", "price" => 10],

    ["name" => "Smartphone", "category" => "Electronics", "price" => 700]

];

 

// Step 2: Sort the array by price in ascending order

usort($products, function($a, $b) {

    return $a['price'] <=> $b['price'];

});

 

// Step 3: Display the sorted product list

echo "Products sorted by price (lowest to highest):\n";

foreach ($products as $product) {

    echo "Name: " . $product["name"] . ", Category: " . $product["category"] . ", Price: $" . $product["price"] . "\n";

}

?>

 

 Explanation:

We use usort() with a custom comparison function to sort the $products array by the price in ascending order.

The foreach loop displays the sorted product list.

Assignment 3: 

Filtering Products by Category

Task:

Filter a multidimensional array of products to include only those in the "Electronics" category and display the filtered list.

Code:

<?php

// Step 1: Create a multidimensional array for products

$products = [

    ["name" => "Laptop", "category" => "Electronics", "price" => 1000],

    ["name" => "Desk Chair", "category" => "Furniture", "price" => 150],

    ["name" => "Book", "category" => "Stationery", "price" => 10],

    ["name" => "Smartphone", "category" => "Electronics", "price" => 700]

];

 

// Step 2: Filter products by category "Electronics"

$electronics = array_filter($products, function($product) {

    return $product['category'] === 'Electronics';

});

 

// Step 3: Display the filtered list

echo "Electronics Products:\n";

foreach ($electronics as $product) {

    echo "Name: " . $product["name"] . ", Price: $" . $product["price"] . "\n";

}

?>

 

 

Explanation:

We use array_filter() with a custom function to select products where the category is "Electronics".

We display the filtered list of electronics products.

Assignment 4: 

Combining Sorting and Filtering

Task:

Create a multidimensional array of products (name, category, price). Filter products by the "Electronics" category, then sort them by price in descending order, and display the results.

Code:

<?php

// Step 1: Create a multidimensional array for products

$products = [

    ["name" => "Laptop", "category" => "Electronics", "price" => 1000],

    ["name" => "Desk Chair", "category" => "Furniture", "price" => 150],

    ["name" => "Book", "category" => "Stationery", "price" => 10],

    ["name" => "Smartphone", "category" => "Electronics", "price" => 700]

];

 

// Step 2: Filter products by category "Electronics"

$electronics = array_filter($products, function($product) {

    return $product['category'] === 'Electronics';

});

 

// Step 3: Sort the filtered electronics by price in descending order

usort($electronics, function($a, $b) {

    return $b['price'] <=> $a['price'];

});

 

// Step 4: Display the sorted and filtered list

echo "Electronics Products Sorted by Price (Highest to Lowest):\n";

foreach ($electronics as $product) {

    echo "Name: " . $product["name"] . ", Price: $" . $product["price"] . "\n";

}

?>

 

               Explanation:

We filter the array to include only "Electronics" products.

We then sort this filtered array by price in descending order.

The foreach loop displays the sorted list of electronics.

These assignments cover practical applications of multidimensional arrays, including creation, manipulation, sorting, and filtering. They help students gain hands-on experience with complex data structures and array functions in PHP.

 

No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template