What is the difference between indexed and associative array?

The indexed array holds elements in an indexed form which is represented by number starting from 0 and incremented by 1. For example:

$season=array(“summer”,”winter”,”spring”,”autumn”);
The associative array holds elements with name. For example:

$salary=array(“Sonoo”=>”350000″,”John”=>”450000″,”Kartik”=>”200000”);

In PHP, indexed arrays and associative arrays are two fundamental data structures used to store collections of data, but they differ in how they organize and access their elements:

  1. Indexed Array:
    • Indexed arrays are also known as numeric arrays.
    • Elements in an indexed array are accessed and referenced using numeric indices (starting from 0).
    • Indexed arrays maintain a sequential order of elements based on their numeric indices.
    • Example:
      php
      $indexedArray = array("apple", "banana", "orange");
      echo $indexedArray[0]; // Outputs: apple
  2. Associative Array:
    • Associative arrays are also known as key-value pairs or hash maps.
    • Elements in an associative array are accessed and referenced using keys (which can be strings or integers).
    • Associative arrays do not maintain a specific order of elements.
    • Example:
      php
      $assocArray = array("name" => "John", "age" => 30, "city" => "New York");
      echo $assocArray["age"]; // Outputs: 30

Key Differences:

  • Access Method: Indexed arrays are accessed using numeric indices, while associative arrays are accessed using keys.
  • Ordering: Indexed arrays maintain a specific order based on numeric indices, while associative arrays do not guarantee any particular order.
  • Usage: Indexed arrays are suitable for ordered collections where elements have a numerical significance (e.g., arrays of items in a list). Associative arrays are used when you need to associate a key with a value, often to represent attributes or properties of something.

In an interview, it’s beneficial to elaborate on these points and provide examples to demonstrate understanding.