Lesson 7: Arrays in PHP

Arrays are one of the most important data structures in PHP. They allow you to store and manage multiple values in a single variable. This lesson will cover the three types of arrays in PHP: Indexed, Associative, and Multidimensional arrays. Additionally, we will explore commonly used array functions.


7.1 Indexed Arrays

What is an Indexed Array?

  • An indexed array stores a series of elements, each assigned an index starting from 0.
  • Elements in an indexed array are accessed using numeric indices.

Creating an Indexed Array

  • Using the array() function:
    php
    $fruits = array("Apple", "Banana", "Cherry");
  • Using shorthand syntax:
    php
    $fruits = ["Apple", "Banana", "Cherry"];

Accessing Elements

php
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Outputs: Apple
echo $fruits[1]; // Outputs: Banana
?>

Adding Elements

php
<?php
$fruits[] = "Orange"; // Adds "Orange" to the array
?>

Looping Through an Indexed Array

php
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . “<br>”;
}
?>

7.2 Associative Arrays

What is an Associative Array?

  • Associative arrays use named keys to access values instead of numeric indices.

Creating an Associative Array

php
<?php
$person = array(
"name" => "Alice",
"age" => 25,
"city" => "New York"
);
?>

Accessing Elements

php
<?php
echo $person["name"]; // Outputs: Alice
echo $person["age"]; // Outputs: 25
?>

Adding Elements

php
<?php
$person["country"] = "USA"; // Adds a new key-value pair
?>

Looping Through an Associative Array

php
<?php
$person = array(
"name" => "Alice",
"age" => 25,
"city" => "New York"
);
foreach ($person as $key => $value) {
echo $key: $value<br>”;
}
?>

7.3 Multidimensional Arrays

What is a Multidimensional Array?

  • Multidimensional arrays are arrays that contain other arrays as elements.

Creating a Multidimensional Array

php
<?php
$students = array(
array("Alice", 25, "New York"),
array("Bob", 22, "Los Angeles"),
array("Charlie", 30, "Chicago")
);
?>

Accessing Elements

php
<?php
echo $students[0][0]; // Outputs: Alice
echo $students[1][2]; // Outputs: Los Angeles
?>

Associative Multidimensional Array

php
<?php
$students = array(
"Alice" => array("age" => 25, "city" => "New York"),
"Bob" => array("age" => 22, "city" => "Los Angeles")
);
echo $students[“Alice”][“city”]; // Outputs: New York
?>

Looping Through a Multidimensional Array

php
<?php
$students = array(
array("Alice", 25, "New York"),
array("Bob", 22, "Los Angeles"),
array("Charlie", 30, "Chicago")
);
foreach ($students as $student) {
echo “Name: $student[0], Age: $student[1], City: $student[2]<br>”;
}
?>

7.4 Array Functions

Commonly Used Array Functions

1. count()

  • Returns the number of elements in an array.
  • Example:
    php
    <?php
    $fruits = ["Apple", "Banana", "Cherry"];
    echo count($fruits); // Outputs: 3
    ?>

2. array_merge()

  • Merges two or more arrays into one.
  • Example:
    php
    <?php
    $array1 = ["a", "b"];
    $array2 = ["c", "d"];
    $merged = array_merge($array1, $array2);
    print_r($merged); // Outputs: Array ( [0] => a [1] => b [2] => c [3] => d )
    ?>

3. array_push()

  • Adds one or more elements to the end of an array.
  • Example:
    php
    <?php
    $fruits = ["Apple", "Banana"];
    array_push($fruits, "Cherry", "Orange");
    print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Orange )
    ?>

4. array_pop()

  • Removes and returns the last element of an array.
  • Example:
    php
    <?php
    $fruits = ["Apple", "Banana", "Cherry"];
    $lastFruit = array_pop($fruits);
    echo $lastFruit; // Outputs: Cherry
    ?>

5. in_array()

  • Checks if a value exists in an array.
  • Example:
    php
    <?php
    $fruits = ["Apple", "Banana", "Cherry"];
    echo in_array("Banana", $fruits) ? "Found" : "Not Found"; // Outputs: Found
    ?>

6. array_keys()

  • Returns all the keys of an array.
  • Example:
    php
    <?php
    $person = ["name" => "Alice", "age" => 25];
    $keys = array_keys($person);
    print_r($keys); // Outputs: Array ( [0] => name [1] => age )
    ?>

7. array_values()

  • Returns all the values of an array.
  • Example:
    php
    <?php
    $person = ["name" => "Alice", "age" => 25];
    $values = array_values($person);
    print_r($values); // Outputs: Array ( [0] => Alice [1] => 25 )
    ?>

8. sort() and rsort()

  • sort(): Sorts an array in ascending order.
  • rsort(): Sorts an array in descending order.
  • Example:
    php
    <?php
    $numbers = [3, 1, 4, 1, 5];
    sort($numbers);
    print_r($numbers); // Outputs: Array ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 )
    ?>

9. array_reverse()

  • Reverses the order of array elements.
  • Example:
    php
    <?php
    $fruits = ["Apple", "Banana", "Cherry"];
    $reversed = array_reverse($fruits);
    print_r($reversed); // Outputs: Array ( [0] => Cherry [1] => Banana [2] => Apple )
    ?>

10. array_search()

  • Searches for a value in an array and returns its key.
  • Example:
    php
    <?php
    $fruits = ["Apple", "Banana", "Cherry"];
    echo array_search("Banana", $fruits); // Outputs: 1
    ?>

Activities and Exercises

  1. Indexed Array:
    • Create an array of your favorite movies and display each movie using a loop.
  2. Associative Array:
    • Create an associative array representing a book (title, author, price) and display its details.
  3. Multidimensional Array:
    • Create an array of students with their name, age, and city. Display all students using nested loops.
  4. Array Functions:
    • Write a script to sort an array of numbers in descending order.

Assignment

Create a PHP script that:

  1. Stores details of products (name, price, category) in a multidimensional array.
  2. Displays all products using a loop.
  3. Sorts the products by price in ascending order.
  4. Searches for a product by name and displays its details.

Summary

In this lesson, you learned:

  • The three types of arrays in PHP: Indexed, Associative, and Multidimensional.
  • How to use key PHP array functions for managing arrays effectively.

Arrays are versatile and foundational in PHP, making them critical for handling complex data structures. Let me know if you need additional examples or exercises!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *