PHP Associative Array

In this tutorial, learn how to create an associative array in PHP and the methods to traverse through it. PHP associative array is useful to create an array with user-defined keys to store data. It has only manually assigned keys for each element.

What is PHP Associative Array?

It is an array in which each element has a manually assigned key of string type. Each key is user-defined and there is no sequence to create elements of an associative array in PHP.

The meaning of an associative array is that each element is associated with a collection of pairs. The keys are unique and come uniquely for the elements. The elements of the associative array is the combination of key-value pairs that you can access using the loop.

How to Create Associative Array in PHP (2 Ways with Examples)

To create an associative array in PHP, there are two ways and you have to choose your preferred way given below:

First Method: Keys are Assigned Within array().

Output

2
5
9

Second Method Keys and Values are Manually Assigned.

Output

2
5
9

Traverse Through Elements to Access PHP

Traversing through an associative array is the process of accessing all the elements. Elements are the collection of key and value pairs. You can use the PHP Foreach loop or PHP For loop to get the key and value of each element one-by-one.

Using the Foreach loop in PHP

Output

Key is: Cycle, Value is: 2
Key is: Bike, Value is: 5
Key is: Car, Value is: 9

Using For loop in PHP

Output

Key is: Cycle, Value is: 2
Key is: Bike, Value is: 5
Key is: Car, Value is: 9

Out of the above two methods, you can use any of them to access elements. However, I recommend using the foreach loop that is faster and easier to get key-value pairs.

Find Length of an Associative Array in PHP

Find the length of an associative array is the process of getting the number of elements present in it. You can use the PHP sizeof() function to get the size of the array. It takes an argument as the associative array variable checks the size of the array as given below:

Output

4

The above example creates an associative array and uses the sizeof() to get the number of elements in an array. The output shows that the length of the associative array is 4 as there are 4 elements in it.