Open In App

Difference between indexed array and associative array

Improve
Improve
Like Article
Like
Save
Share
Report

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 the keys is associated with its own specific value. 

Example 1:

PHP




<?php
  
// Declaring an array
$arr = array(1, 2, 3, 4, 5);
  
echo('Array : ');
  
// Print the array
print_r($arr);
  
?>


Output

Array : Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example 2: Individual values can be assigned to the array indices values using integer index values as indicated in the below code snippet.

PHP




<?php
    
// Declaring an array
$arr = array();
  
// Assigning values
$arr[0] = 5;
$arr[1] = 6;
  
print("Array : ");
print_r($arr);
  
?>


Output

Array : Array
(
    [0] => 5
    [1] => 6
)

Associative array: An associative array is stored in the form of key-value pair. This type of array is where the key is stored in the numeric or string format. 

Example 1:

PHP




<?php
    
// Declaring an array
$arr = array(
      "Java" => "Spring Boot"
      "Python" => "Django"
      "PHP" => "CodeIgniter"
);
  
// Assigning values
print("Array : ");
print_r($arr);
  
?>


Output

Array : Array
(
    [Java] => Spring Boot
    [Python] => Django
    [PHP] => CodeIgniter
)

The array[key] = value expression can be used to assign individual values as components of the array.   

Example 2:

PHP




<?php
  
// Declaring an array
$arr = array();
  
// Declaring key-value pairs
$arr['Python'] = "Django";
$arr['Java'] = "SpringBoot";
$arr['PHP'] = "CodeIgniter";
  
print("Array : ");
print_r($arr);
  
?>


Output

Array : Array
(
    [Python] => Django
    [Java] => SpringBoot
    [PHP] => CodeIgniter
)

Difference between Indexed array and associative array:

                                 Indexed Array                       Associative Array
The keys of an indexed array are integers which start at 0. Keys may be strings in the case of an associative array.
They are like single-column tables. They are like two-column tables.
They are not maps. They are known as maps. 


Last Updated : 22 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads