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
$fruits = [“Apple”, “Banana”, “Cherry”];
echo $fruits[0]; // Outputs: Apple
echo $fruits[1]; // Outputs: Banana
?>

Adding Elements

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

Looping Through an Indexed Array

<?php
$fruits = [“Apple”, “Banana”, “Cherry”];

foreach ($fruits as $fruit) {
echo $fruit . “
“;
}
?>


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
$person = array(
“name” => “Alice”,
“age” => 25,
“city” => “New York”
);
?>

Accessing Elements

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

Adding Elements

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

Looping Through an Associative Array

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

foreach ($person as $key => $value) {
echo “$key: $value
“;
}
?>


7.3 Multidimensional Arrays

What is a Multidimensional Array?

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

Creating a Multidimensional Array

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

Accessing Elements

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

Associative Multidimensional Array

<?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
$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]
“;
}
?>


7.4 Array Functions

Commonly Used Array Functions

1. count()

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

2. array_merge()

  • Merges two or more arrays into one.
  • Example:
  • <?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
    $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
    $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
    $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
    $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
    $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
    $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
    $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
    $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 *