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

Sunday, September 1, 2024

Class 6: Arrays - Part 1

Class 6: Arrays - Part 1

Objective:

Learn about arrays, including indexed and associative arrays.

Outcome:

Students will be able to create, access, and manipulate both indexed and associative arrays using built-in array functions.

1. Introduction to Arrays

Why Use of an Array?

Suppose we want to store five names and print them accordingly. This can be easily done by the use of five different string variables. But if instead of five, the number rises to a hundred, then it would be really difficult for the user or developer to create so many different variables. Here array comes into play and helps us to store every element within a single variable and also allows easy access using an index or a key.

1. What Are Arrays?

An array is a data structure that stores one or more similar type of values in a single value. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key.  

For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name.

PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.

An array is a special variable in PHP that can hold multiple values. Instead of creating a new variable for each value, you can store all related values in a single array.

Think of an array as a list. For example, if you have a list of fruits, instead of creating separate variables like $fruit1, $fruit2, and so on, you can store all the fruits in one array.

Arrays in PHP are data structures that allow you to store multiple values in a single variable. They are extremely useful for managing lists of data, such as names, numbers, or other types of information.


Advantage of PHP Array

  1. Dynamic Size:    PHP arrays are dynamic, meaning you can add or remove elements without the need to declare a fixed size. This flexibility makes arrays suitable for handling varying amounts of data.
  2. Versatility:    PHP arrays can store different data types within the same array. You can have a mix of strings, integers, floats, and even other arrays as elements within a single array.
  3. Indexed and Associative Arrays:   PHP supports both indexed arrays (numeric keys) and associative arrays (string keys). This flexibility allows you to choose the most appropriate type based on your specific use case.
  4. Efficient Data Retrieval:   PHP arrays provide fast and efficient data retrieval. You can quickly access an element using its key or index, making it suitable for scenarios where fast lookups are essential.
  5. Built-in Array Functions:   PHP comes with a rich set of built-in array functions that make it easy to manipulate and process array data. Functions like count(), foreach(), array_map(), and array_filter() simplify common array operations.
  6. Array Iteration:   PHP provides convenient ways to iterate through arrays, such as using foreach loops. This makes it easy to perform actions on each element of an array without dealing with explicit indexing.   
  7. Passing Arrays to Functions:   PHP allows you to pass arrays to functions, making it convenient to work with collections of data. Functions can receive arrays as arguments, enabling modular and reusable code.   
  8. Serialization and Unserialization:  PHP provides functions like serialize() and unserialize() that allow you to convert arrays into a string representation and vice versa. This is useful for storing arrays in databases or transferring them between different parts of an application.
  9. Sorting and Searching:  PHP provides functions for sorting arrays (sort(), asort(), ksort(), etc.) and searching for specific values (in_array(), array_search(), etc.), making it easy to organize and retrieve data. 
  10. JSON Representation: PHP arrays can be easily converted to JSON format using the json_encode() function. This is particularly useful for exchanging data between a PHP backend and a JavaScript frontend.
  11. Memory Efficiency:     PHP arrays are implemented efficiently in terms of memory usage, making them suitable for handling large datasets without significant overhead.

Types of Arrays:

1.Indexed Arrays:

These are arrays where the keys are automatically assigned numeric indexes starting from 0.

Example: A list of fruits.

Creating Indexed Arrays

Indexed arrays use numeric indexes to access their elements. These indexes start at 0.

You can create an indexed array using the array() function or the shorthand [] syntax.

Example:

<?php

$fruits = array("Apple", "Banana", "Cherry");  // Using array() function

$colors = ["Red", "Green", "Blue"];            // Using shorthand []

?>

 

 

Accessing Array Elements:

You can access elements of an indexed array using the index number.

Example:

<?php

echo $fruits[0];  // Output: Apple

echo $colors[2];  // Output: Blue

?>

 

 Modifying Array Elements:

You can modify elements in an array by assigning a new value to a specific index.

Example:

<?php

$fruits[1] = "Mango";  // Changing Banana to Mango

echo $fruits[1];       // Output: Mango

?>

 

 

2.Associative Arrays:

These arrays use named keys that you assign to them. Instead of numeric indexes, associative arrays use strings as keys.

Example: A list of students and their grades.

Creating Associative Arrays

Associative arrays use named keys to store and access data. This is useful when you want to associate a value with a specific identifier.

You can create associative arrays by specifying keys and values.

Example:

<?php

$grades = array("Alice" => 90, "Bob" => 85, "Charlie" => 88);  // Using array() function

$ages = ["Alice" => 25, "Bob" => 30, "Charlie" => 28];         // Using shorthand []

?>

 

 Accessing Array Elements:

You can access elements in an associative array using their keys.

Example:

<?php

echo $grades["Alice"];  // Output: 90

echo $ages["Charlie"];  // Output: 28

?>

 

 

Modifying Array Elements:

You can change the value associated with a specific key.

Example:

<?php

$grades["Bob"] = 95;  // Changing Bob's grade from 85 to 95

echo $grades["Bob"];  // Output: 95

?>

 

 

4. Built-in Array Functions

PHP provides several built-in functions to work with arrays. Here are a few essential ones:

count(): Returns the number of elements in an array.

array_push(): Adds one or more elements to the end of an array.

array_pop(): Removes the last element from an array.

array_keys(): Returns all the keys of an array.

array_values(): Returns all the values of an array.

Examples:

<?php

$fruits = ["Apple", "Banana", "Cherry"];

echo count($fruits);          // Output: 3

array_push($fruits, "Orange");

print_r($fruits);             // Output: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Orange )

array_pop($fruits);

print_r($fruits);             // Output: Array ( [0] => Apple [1] => Banana [2] => Cherry )

$keys = array_keys($grades);

print_r($keys);               // Output: Array ( [0] => Alice [1] => Bob [2] => Charlie )

$values = array_values($grades);

print_r($values);             // Output: Array ( [0] => 90 [1] => 95 [2] => 88 )

?>

 

 

5. Conclusion

Arrays are fundamental structures in PHP that allow you to store and manage lists of data efficiently. Understanding how to create, access, and manipulate both indexed and associative arrays will enable you to handle complex data sets and improve the functionality of your PHP scripts. In the next class, we will explore more advanced array operations and functions.

Assignments

Assignment 1: 

Create and Manipulate an Indexed Array

Task:

Create an indexed array of five different fruits. Display the list of fruits, then replace one of the fruits with another fruit and display the updated list.

Code:

<?php

// Step 1: Create an indexed array with five different fruits

$fruits = ["Apple", "Banana", "Cherry", "Mango", "Orange"];

// Step 2: Display the list of fruits

echo "Original list of fruits:\n";

foreach ($fruits as $fruit) {

    echo $fruit . "\n";

}

// Step 3: Replace one of the fruits (e.g., Banana) with another fruit (e.g., Pineapple)

$fruits[1] = "Pineapple";

// Step 4: Display the updated list of fruits

echo "\nUpdated list of fruits:\n";

foreach ($fruits as $fruit) {

    echo $fruit . "\n";

}

?>

 

 Explanation:

  1. We create an indexed array $fruits with five elements.
  2. We use a foreach loop to display each fruit.
  3. We replace the second fruit (Banana) with Pineapple by assigning a new value to the index 1.
  4. We display the updated list using another foreach loop.

Assignment 2: 

Create and Access an Associative Array

Task:

Create an associative array that stores the names of three students and their corresponding grades. Display each student's name and grade.

Code:

<?php

// Step 1: Create an associative array with students' names and grades

$grades = [

    "Alice" => 90,

    "Bob" => 85,

    "Charlie" => 88

];

// Step 2: Display each student's name and grade

echo "Students and their grades:\n";

foreach ($grades as $name => $grade) {

    echo "$name: $grade\n";

}

?>

 

 Explanation:

We create an associative array $grades where the keys are student names and the values are their grades.

We use a foreach loop to display each student's name and grade.

Assignment 3: 

Use Built-in Functions with Arrays

Task:

Create an indexed array of colors. Add a new color to the array, remove the last color, and then display the keys and values of the array.

Code:

<?php

// Step 1: Create an indexed array with some colors

$colors = ["Red", "Green", "Blue", "Yellow"];

 

// Step 2: Add a new color to the array using array_push()

array_push($colors, "Purple");

 

// Step 3: Remove the last color from the array using array_pop()

array_pop($colors);

 

// Step 4: Display the keys and values of the array

echo "Array keys:\n";

$keys = array_keys($colors);

foreach ($keys as $key) {

    echo $key . "\n";

}

 

echo "\nArray values:\n";

$values = array_values($colors);

foreach ($values as $value) {

    echo $value . "\n";

}

?>

 

 Explanation:

  1. We start by creating an indexed array $colors with four colors.
  2. We use array_push() to add a new color (Purple) to the end of the array.
  3. We use array_pop() to remove the last color from the array.
  4. We display the keys and values of the array separately using array_keys() and array_values() functions.

Assignment 4: 

Create a Multi-dimensional Array

Task:

Create a multi-dimensional array to store information about three cars (make, model, and year). Display the information for each car.

Code:

<?php

// Step 1: Create a multi-dimensional array to store cars' information

$cars = [

    ["Make" => "Toyota", "Model" => "Corolla", "Year" => 2020],

    ["Make" => "Honda", "Model" => "Civic", "Year" => 2019],

    ["Make" => "Ford", "Model" => "Focus", "Year" => 2018]

];

 

// Step 2: Display the information for each car

echo "Cars information:\n";

foreach ($cars as $car) {

    echo "Make: " . $car["Make"] . ", Model: " . $car["Model"] . ", Year: " . $car["Year"] . "\n";

}

?>

 

 Explanation:

  1. We create a multi-dimensional array $cars where each element is an associative array containing the make, model, and year of a car.
  2. We use a foreach loop to iterate through the array and display each car's information.

Assignment 5: 

Sort an Associative Array

Task:

Create an associative array of five countries and their populations. Sort the array by population (in ascending order) and display the sorted list.

Code:

<?php

// Step 1: Create an associative array with countries and their populations

$populations = [

    "China" => 1400000000,

    "India" => 1350000000,

    "USA" => 331000000,

    "Indonesia" => 273000000,

    "Pakistan" => 220000000

];

 

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

asort($populations);

 

// Step 3: Display the sorted list

echo "Countries sorted by population:\n";

foreach ($populations as $country => $population) {

    echo "$country: $population\n";

}

?>

 

 Explanation:

  1. We create an associative array $populations with countries as keys and their populations as values.
  2. We use asort() to sort the array by population in ascending order, keeping the association between keys and values intact.
  3. We display the sorted list using a foreach loop.


These assignments cover a range of concepts related to arrays in PHP, from basic creation and manipulation to using built-in functions and sorting arrays.


No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template