The Wayback Machine - https://web.archive.org/web/20240914114248/https://www.geeksforgeeks.org/multidimensional-associative-array-in-php/
Open In App

Multidimensional Associative Array in PHP

Last Updated : 31 Jul, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation.

Creation: We can create a multidimensional associative array by mapping an array containing a set of key and value pairs to the parent key.
The below program demonstrate how to create a multidimensional associative array:




<?php
  
$languages = array();
  
$languages['Python'] = array(
    "first_release" => "1991", 
    "latest_release" => "3.8.0", 
    "designed_by" => "Guido van Rossum",
    "description" => array(
        "extension" => ".py", 
        "typing_discipline" => "Duck, dynamic, gradual",
        "license" => "Python Software Foundation License"
    )
);
  
$languages['PHP'] = array(
    "first_release" => "1995", 
    "latest_release" => "7.3.11", 
    "designed_by" => "Rasmus Lerdorf",
    "description" => array(
        "extension" => ".php", 
        "typing_discipline" => "Dynamic, weak",
        "license" => "PHP License (most of Zend engine
             under Zend Engine License)"
    )
);
  
print_r($languages);
  
?>


Output:

Array
(
    [Python] => Array
        (
            [first_release] => 1991
            [latest_release] => 3.8.0
            [designed_by] => Guido van Rossum
            [description] => Array
                (
                    [extension] => .py
                    [typing_discipline] => Duck, dynamic, gradual
                    [license] => Python Software Foundation License
                )

        )

    [PHP] => Array
        (
            [first_release] => 1995
            [latest_release] => 7.3.11
            [designed_by] => Rasmus Lerdorf
            [description] => Array
                (
                    [extension] => .php
                    [typing_discipline] => Dynamic, weak
                    [license] => PHP License (most of Zend engine
             under Zend Engine License)
                )

        )

)

Explanation: In above program, parent index are Python and PHP. The parent key is associated with an array of sets of keys with constant values. The last key i.e. description of each parent key has been associated with another array of the set of keys and constant values. Here Python and PHP are parent key for first_release, latest_release, designed_by and description whereas description is parent key for the extension, typing_discipline, and license.

Retrieving Values: We can retrieve the value of multidimensional array using the following method:

  1. Using key: We can use key of the associative array to directly retrieve the data value.

    Example:




    <?php
      
    $languages = array();
      
    $languages['Python'] = array(
        "first_release" => "1991", 
        "latest_release" => "3.8.0", 
        "designed_by" => "Guido van Rossum",
        "description" => array(
            "extension" => ".py", 
            "typing_discipline" => "Duck, dynamic, gradual",
            "license" => "Python Software Foundation License"
        )
    );
      
    print_r($languages['Python']['description']);
    echo $languages['Python']['latest_release'];
      
    ?>

    
    

    Output:

    Array
    (
        [extension] => .py
        [typing_discipline] => Duck, dynamic, gradual
        [license] => Python Software Foundation License
    )
    3.8.0
    
  2. Using foreach loop: We can use foreach loop to retrieve value of each key associated inside the multidimensional associative array.
    Example:




    <?php
      
    $languages = array();
      
    $languages['Python'] = array(
        "first_release" => "1991", 
        "latest_release" => "3.8.0", 
        "designed_by" => "Guido van Rossum",
        "description" => array(
            "extension" => ".py", 
            "typing_discipline" => "Duck, dynamic, gradual",
            "license" => "Python Software Foundation License"
        )
    );
      
    foreach ($languages as $key => $value) {
        echo $key . "\n";
        foreach ($value as $sub_key => $sub_val) {
                      
            // If sub_val is an array then again
            // iterate through each element of it
            // else simply print the value of sub_key
            // and sub_val
            if (is_array($sub_val)) {
                echo $sub_key . " : \n";
                foreach ($sub_val as $k => $v) {
                    echo "\t" .$k . " = " . $v . "\n";
                }
            } else {
                echo $sub_key . " = " . $sub_val . "\n";
            }
        }
    }
      
    ?>

    
    

    Output:

    Python
    first_release = 1991
    latest_release = 3.8.0
    designed_by = Guido van Rossum
    description : 
        extension = .py
        typing_discipline = Duck, dynamic, gradual
        license = Python Software Foundation License
    

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Previous Article
Next Article

Similar Reads

How to check an array is associative or sequential in PHP?
In PHP there is no need to write the variable type before the variable because it is loosely-typed. It takes datatype from user defined values that are stored in it. Arrays in PHP is a type of data structure that allows to store multiple elements of similar data type under a single variable thereby saving the effort of creating a different variable
2 min read
How to access an associative array by integer index in PHP?
There are two types of arrays in PHP, indexed and associative arrays. In case of indexed array strict numeric indexing is followed but in case of associative array there are keys corresponding to each element. The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, acces
3 min read
PHP program to add item at the beginning of associative array
In PHP associative array is the type of array where the index need not to be strictly sequential like indexed array. Normally add a new element in an existing associative array it will get appended at the end of that array. Example: &lt;?php // Existing array $arr = array('one' =&gt; 1, 'two' =&gt; 2); // New element $arr['zero'] = 0; // Final arra
3 min read
How to get numeric index of associative array in PHP?
In PHP we can associate name/label with each array elements using =&gt; symbol. This is very helpful as it is easy to remember the element because each element is represented by the label rather than the index value. Using array_keys() function: The array_keys() function is an inbuilt function in PHP which is used to return either all the keys of a
1 min read
How to sort an associative array by key in PHP?
Sorting an associative array by key is a common task in PHP, especially when you need to organize data alphabetically or numerically based on keys. PHP provides built-in functions to accomplish this task efficiently, allowing developers to rearrange the order of elements within an associative array based on their keys. Approach:Using ksort() Functi
2 min read
How to remove a key and its value from an associative array in PHP ?
Given an associative array containing array elements the task is to remove a key and its value from the associative array. Examples: Input : array( "name" =&gt; "Anand", "roll"=&gt; "1") Output : Array ( [roll] =&gt; 1 ) Input : array( "1" =&gt; "Add", "2" =&gt; "Multiply", "3" =&gt; "Divide") Output : Array ( [2] =&gt; Multiply [3] =&gt; Divide )
2 min read
How to loop through an associative array and get the key in PHP?
Associative arrays are used to store key-value pairs. For example, to store the marks of the different subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject’s names as the keys in our associative array, and the value would be their respective marks gained. In associa
3 min read
Iterate associative array using foreach loop in PHP
Given two arrays arr1 and arr2 of size n. The task is to iterate both arrays for each loop. Both arrays can combine into a single array using a for each loop. Array: Arrays in PHP are a type of data structure that allows the storing of multiple elements of similar data type under a single variable thereby saving the effort of creating a different v
3 min read
How to Check if a Value Exists in an Associative Array in PHP?
Given an Associative array, the task is to check whether a value exists in the associative array or not. There are two methods to check if a value exists in an associative array, these are - using in_array(), and array_search() functions. Let's explore each method with detailed explanations and code examples. Table of Content Using in_array() Funct
2 min read
Sort an Associative Array by Key in PHP
Given an Associative Array, the task is to sort the associative array by its keys in PHP. There are different methods to sort Associative Array by keys, these are described below: Table of Content Using ksort() FunctionUsing uksort() FunctionConverting to a Regular Array for SortingUsing array_multisort() FunctionAddeUsing ksort() FunctionThe ksort
3 min read
Convert an object to associative array in PHP
An object is an instance of a class. It is simply a specimen of a class and has memory allocated. The array is the data structure that stores one or more similar types of values in a single name but an associative array is different from a simple PHP array. An array that contains a string index is called an associative array. It stores element valu
3 min read
How to sort an Array of Associative Arrays by Value of a Given Key in PHP ?
Each entry in the associative array is characterized by a unique key-value pair. An array can contain singular data types belonging to variables or other arrays as its elements. There are multiple ways to sort an array of associative arrays by the value of a specified key. Table of Content Using the array_multisort() methodUsing the usort() methodU
6 min read
How to Get All Values from an Associative Array in PHP?
Given an Associative Array, the task is to get all values from the associative array in PHP. To get all the values from an associative array, you can use various approaches such as foreach loop, array_values() function, and array_map() function. In this article, we will explore each approach with detailed explanations and code examples. Table of Co
3 min read
How to Get All Keys of an Associative Array in PHP?
Given an Associative array, the task is to get all the keys of the associative array in PHP. There are two approaches to get all keys from the associative array, these are - using array_keys(), and foreach loop. In this article, we will explore these approaches with examples. Table of Content Approach 1: Using the array_keys() FunctionApproach 2: U
2 min read
How to Check if a Key Exists in an Associative Array in PHP?
Given an Associative array, the task is to check whether a key exists in the associative array or not. There are two methods to check if a key exists in an associative array, these are - using array_key_exists(), and isset() functions. Let's explore each method with detailed explanations and code examples. Table of Content Using array_key_exists()
3 min read
PHP multidimensional array search by value
In PHP, multidimensional array search refers to searching a value in a multilevel nested array. There are various techniques to carry out this type of search, such as iterating over nested arrays, recursive approaches and inbuilt array search functions. Iterative Approach: Iterating over the array and searching for significant match is the simplest
4 min read
Sort a multidimensional array by date element in PHP
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements. Syntax: boolean usort( $array, "function_name") Parameter
2 min read
Convert multidimensional array to XML file in PHP
Given a multi-dimensional array and the task is to convert this array into an XML file. To converting the multi-dimensional array into an xml file, create an XML file and use appendChild() and createElement() function to add array element into XML file. Example: First, create a PHP Multidimensional Array for converting that array into the XML file
2 min read
Converting all keys into snake case in multidimensional array in PHP
In the Snake case, we need to convert a given sentence or a word to a style of writing where all upper case characters will be replaced with lower case and all the gaps will be replaced with an underscore(_). In this article, we will see how to find the snake case of the all keys of a given array. Here, we need to check each of the elements present
4 min read
How to search by key=&gt;value in a multidimensional array in PHP ?
In PHP, multidimensional array search refers to searching a key=&gt;value in a multilevel nested array. This search can be done either by the iterative or recursive approach. Table of Content Recursive ApproachIterative ApproachUsing array_filter() FunctionRecursive Approach:Check if the key exists in a multidimensional array and if the value of a
4 min read
How to check an array is multidimensional or not in PHP ?
Given an array (single-dimensional or multi-dimensional) the task is to check whether the given array is multi-dimensional or not. Below are the methods to check if an array is multidimensional or not in PHP: Table of Content Using rsort() functionUsing Nested foreach LoopUsing a Recursive FunctionUsing json_encode() and json_decode() Functions:Usi
4 min read
How to merge the duplicate value in multidimensional array in PHP?
To merge the duplicate value in a multidimensional array in PHP, first, create an empty array that will contain the final result. Then we iterate through each element in the array and check for its duplicity by comparing it with other elements. If duplicity is found then first merge the duplicate elements and then push it to the final array else di
4 min read
Associative Arrays in PHP
Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject's names as the keys in our associative array, and the value would be their respective marks gained. Example: Here
3 min read
Difference between indexed array and associative array
An array is a collection of objects that contain a group of variables stored under the same name. All the elements belong to the same data type, i.e. string, integers, or lists. Keys are unique in the case of both indexed and associative arrays. Indexed array: Indexed array is an array with a numeric key. It is basically an array wherein each of th
2 min read
Multidimensional arrays in PHP
Multi-dimensional arrays are such type of arrays which stores an another array at each index instead of single element. In other words, define multi-dimensional arrays as array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays
4 min read
How to Use Foreach Loop with Multidimensional Arrays in PHP?
Given a Multi-dimensional array, the task is to loop through array in PHP. The foreach loop is a convenient way to iterate over arrays in PHP, including multidimensional arrays. When dealing with multidimensional arrays, you can use nested foreach loops to access and process each element. In this article, we will explore how to use foreach loops to
2 min read
How to use Associative Array in TypeScript ?
Typescript Associative arrays are objects in which indexes are replaced by user-defined keys. Associative Array can be used like a regular array, but the only difference is that it can be accessed using strings instead of numbers. Syntax:let associativeArray: { [key: string]: string } = { key1: "value1", key2: "value2",};console.log(associativeArra
2 min read
How to get a list of associative array keys in JavaScript ?
Associative Array: Associative arrays are used to store key-value pairs. For example, to store the marks of the different subjects of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subjects’ names as the keys in our associative array, and the value would be their respective mark
4 min read
How to remove Objects from Associative Array in JavaScript ?
In this article, we are going to learn about removing Objects from Associative Array in Javascript, In JavaScript, you can remove objects from an associative array (also known as an object) using the following methods. Table of Content Using JavaScript delete operatorUsing JavaScript Array.filter() method Using Lodash _.omit methodUsing Object.assi
4 min read
Calculate the length of an associative array using JavaScript
In JavaScript, we have normal arrays in which an element is present at a particular index. Whereas Associative arrays are basically Objects in JavaScript where the index is replaced with user-defined keys. Basically, we can say that it stores Key-Value pairs. Syntax: let arr = { key1: 'value'1, key2: 'value2', key3: 'value3'}Here, arr is the associ
4 min read