Complete Tutorial of Associative Arrays

What is Associative Arrays?

Key value pairs are stored in associative arrays. For example, a numerically indexed array might not be the ideal choice for storing a student’s marks from several subjects in an array. Instead, we might use the names of the subjects as the keys in our associative array, with their appropriate marks as the value.

Example:-

Output:

Some Features of Associative Arrays?

Associative arrays are similar to numeric arrays in appearance, but differ in terms of index. An associative array’s index is a string that establishes a strong relationship between key and value.

For storing employee wages in an array, a numerically indexed array is not the ideal choice. Instead, you may create an associative list with the workers’ names as keys and their salary as the value.

  • The variable’s name is “$variable nameā€¦”, the element’s access index number is “[‘key name’],” and the array element’s value is “value.”
  • Consider the following scenario: you have a group of people and want to assign gender to each of them based on their names.
  • You may achieve this by using an associative list.
  • You can do so by using the code below.

Traversing the Associative Array:-

Loops may be used to go over associative arrays. The associative array can be looped through in two different ways. Using the for loop first, and then the foreach loop second.

Example:-

In this case, the array keys() function is used to identify indices with provided names, and the count() method is used to count the number of indices in associative arrays.

Output:-

Creating an associative array of mixed types:-

Output:-

Tagged : / / / / / / / / / / /