Associative Arrays

Arrays may have non-numeric indexes.

Inserting Data

Data can be inserted by specifying certain key and value.

Example:

In this example, 2 records have been inserted.

Accessing Values

Values can be accessed via their keys.

Let's look at the following example:

Output:

The key-value pair for Coke is set at line 4 and accessed at line 7.

Not Set Key

Accessing key that's not set in the array results in warning and null value.

Let's look at the following example:

Output:

The array doesn't contain any Coke key, so $drinks["Coke"] has a value of null.

Iterating Elements

Let's have a program in which students scores are stored in array and printed afterwards.

Output:

Removing Elements

That's done via the unset function like in this example:

Checking if key exists

It can be done via the isset function like in the following code:

Output:

Water key is not set thus Water is not printed.

Size

Size is the count of the key-value pairs.

It can be accessed via the count function.

Let's look at this example:

Output:

4 records were inserted and 1 is deleted afterwards. This makes for 3 key-value pairs.