Multidimensional Associative Array in PHP

By Shahnail Khan Last updated : February 19, 2024

PHP, a versatile scripting language, offers a robust feature known as multidimensional associative arrays. This feature allows developers to organize and manipulate data in a structured and hierarchical manner, quite useful for handling complex information. In this article, we'll see how the creation, manipulation, and retrieval of data from multidimensional associative arrays is done along with relevant examples.

Understanding Multidimensional Associative Arrays

In PHP, a multidimensional associative array is created by mapping arrays containing key-value pairs to a parent key.

Example of Multidimensional Associative Array

Let's consider a practical example by taking a bookstore's inventory:

<?php
$book__store = array();
//Creating a bookstore having fiction books
$book_store['Fiction'] = array(
    "books" => array(
        "The Great Gatsby" => array("author" => "F. Scott Fitzgerald", "price" => 15.99),
        "To Kill a Mockingbird" => array("author" => "Harper Lee", "price" => 12.50)
    )
);
//Creating a bookstore which has non-fiction books
$book_store['Non-Fiction'] = array(
    "books" => array(
        "Sapiens" => array("author" => "Yuval Noah Harari", "price" => 18.95),
        "The Power of Habit" => array("author" => "Charles Duhigg", "price" => 14.75)
    )
);

print_r($book_store);
?>

Output

The output of the above example is:

Array
(
    [Fiction] => Array
        (
            [books] => Array
                (
                    [The Great Gatsby] => Array
                        (
                            [author] => F. Scott Fitzgerald
                            [price] => 15.99
                        )

                    [To Kill a Mockingbird] => Array
                        (
                            [author] => Harper Lee
                            [price] => 12.5
                        )

                )

        )

    [Non-Fiction] => Array
        (
            [books] => Array
                (
                    [Sapiens] => Array
                        (
                            [author] => Yuval Noah Harari
                            [price] => 18.95
                        )

                    [The Power of Habit] => Array
                        (
                            [author] => Charles Duhigg
                            [price] => 14.75
                        )

                )

        )

)

In this example, the $bookstore array is organized into two main categories: 'Fiction' and 'Non-Fiction.' Each category is associated with an array of books, and each book has its own set of attributes such as author and price.

Retrieving Values from Multidimensional Arrays

There are many ways to retrieve values from multidimensional arrays. Let's have a look at different ways with relevant examples

.

1. Using key

Let's say we want to know the price of the book named "The Great Gatsby". We have defined multidimensional associative arrays, from which we can get easily identify the price.

Example to Access Multidimensional Associative Array Using Key

<?php
$book__store = array();
//Creating a bookstore having fiction books
$book_store['Fiction'] = array(
    "books" => array(
        "The Great Gatsby" => array("author" => "F. Scott Fitzgerald", "price" => 15.99),
        "To Kill a Mockingbird" => array("author" => "Harper Lee", "price" => 12.50)
    )
);
//Creating a bookstore which has non-fiction books
$book_store['Non-Fiction'] = array(
    "books" => array(
        "Sapiens" => array("author" => "Yuval Noah Harari", "price" => 18.95),
        "The Power of Habit" => array("author" => "Charles Duhigg", "price" => 14.75)
    )
);
echo $book_store['Fiction']['books']['The Great Gatsby']['price']; // Result: 15.99
?>

The output of the above example is:

15.99

Explanation:

This line of code echo $book_store['Fiction']['books']['The Great Gatsby']['price']; retrieves the price of the fiction book named "The Great Gatsby" and then displays it (which is '15.99' in this case).

2. Using foreach Loop

You can also access the elements of a multidimensional associate array using the foreach loop.

Example to Access Multidimensional Associative Array Using foreach Loop

<?php
$book__store = array();
//Creating a bookstore having fiction books
$book_store['Fiction'] = array(
    "books" => array(
        "The Great Gatsby" => array("author" => "F. Scott Fitzgerald", "price" => 15.99),
        "To Kill a Mockingbird" => array("author" => "Harper Lee", "price" => 12.50)
    )
);
//Creating a bookstore which has non-fiction books
$book_store['Non-Fiction'] = array(
    "books" => array(
        "Sapiens" => array("author" => "Yuval Noah Harari", "price" => 18.95),
        "The Power of Habit" => array("author" => "Charles Duhigg", "price" => 14.75)
    )
);
foreach ($book_store as $category => $details) {
    echo "Category: $category\n";
    foreach ($details['books'] as $title => $attributes) {
        echo "$title by {$attributes['author']} - \${$attributes['price']}\n";
    }
    echo "\n";
}
?>

The output of the above example is:

Category: Fiction
The Great Gatsby by F. Scott Fitzgerald - $15.99
To Kill a Mockingbird by Harper Lee - $12.5

Category: Non-Fiction
Sapiens by Yuval Noah Harari - $18.95
The Power of Habit by Charles Duhigg - $14.75

Explanation

The foreach loop iterates through each category (Fiction & Non-fiction), and then within each category, it iterates through the books and prints the book title, author, and price.

Practical Use Cases of PHP Multidimensional Associative Array

1. Managing User Data

Suppose we have different users' data and we need to store that data, including their personal details and preferences:

<?php
$users = array();

$users['SK'] = array(
    "personal_info" => array("name" => "SK", "age" => 22, "email" => "[email protected]"),
    "preferences" => array("theme" => "dark", "language" => "English")
);

$users['JaneSmith'] = array(
    "personal_info" => array("name" => "Jane Smith", "age" => 25, "email" => "[email protected]"),
    "preferences" => array("theme" => "light", "language" => "Spanish")
);

print_r($users);
?>

Output:

Array
(
    [SK] => Array
        (
            [personal_info] => Array
                (
                    [name] => SK
                    [age] => 22
                    [email] => [email protected]
                )

            [preferences] => Array
                (
                    [theme] => dark
                    [language] => English
                )

        )

    [JaneSmith] => Array
        (
            [personal_info] => Array
                (
                    [name] => Jane Smith
                    [age] => 25
                    [email] => [email protected]
                )

            [preferences] => Array
                (
                    [theme] => light
                    [language] => Spanish
                )

        )

)

In this example, each user is a parent key associated with arrays containing personal information and preferences.

2. Representing Graph Data

Let's represent a graph using a multidimensional array.

<?php
$graph = array(
    "A" => array("B", "C"),
    "B" => array("A", "D"),
    "C" => array("A", "E"),
    "D" => array("B"),
    "E" => array("C")
);

print_r($graph);
?>

Output:

Array
(
    [A] => Array
        (
            [0] => B
            [1] => C
        )

    [B] => Array
        (
            [0] => A
            [1] => D
        )

    [C] => Array
        (
            [0] => A
            [1] => E
        )

    [D] => Array
        (
            [0] => B
        )

    [E] => Array
        (
            [0] => C
        )

)

Takeaway

Multidimensional associative arrays in PHP provide a powerful and flexible way to organize, manage, and retrieve complex data structures. Whether dealing with bookstore inventories, user data, or graph representations, the versatility of multidimensional arrays shines through. Developers can use this feature to create organized and efficient code, as PHP can very well handle diverse data scenarios. Understanding and mastering multidimensional associative arrays is a key skill for any PHP developer, which opens the door to efficient data management and manipulation.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.