Skip to content
Home » How to make an associative array in PHP

How to make an associative array in PHP

An array is a fundamental data structure in programming. Thus, beginners find themselves learning it at the very beginning of their programming journey. We are often used to arrays that store data as a list. But, associative arrays are different because they store key-value pairs rather than just listing items.

Here we’ll see how to make an associative array and also explore it from a practical perspective.

Option 1 – Make an associative array in PHP using the array keyword

One way to make an associative array in PHP is to use the array keyword. We can pass more than one key-value pair separated by commas to the array keyword. The general syntax looks like.

$array_variable = array(“key”=>”value”,...);

The key and the value can be any valid PHP data type. The code example creates an array with employee names as keys and their ages as values.

?php
//An associative array with employee-age as key-value pairs.
$employee_age = array("Anna"=>21,"Mike"=>24,"Benjamin"=>25,"Mark"=>29,"Sarah"=>30);
 
//Prints the $employee_age array 
print_r($employee_age);
 
/*
OUTPUT
Array
(
    [Anna] => 21
    [Mike] => 24
    [Benjamin] => 25
    [Mark] => 29
    [Sarah] => 30
)
*/
?>

There’s another way which creates key-value pairs one at a time, let’s see that.

Option 2 – Make an associative array in PHP using square bracket syntax

The square bracket syntax is another way to make an associate array in PHP. This option adds one key and value at a time. The general syntax looks like.

$employee_age[$key] = $value;
<?php
 
//The following lines of code introduces key-value pairs in $employee_age array.
$employee_age["Anna"] = 21;
$employee_age["Mike"] = 24;
$employee_age["Benjamin"] = 25;
$employee_age["Mark"] = 29;
$employee_age["Sarah"] = 30;
 
//Prints the $employee_age array 
print_r($employee_age);
 
/*
OUTPUT
Array
(
    [Anna] => 21
    [Mike] => 24
    [Benjamin] => 25
    [Mark] => 29
    [Sarah] => 30
)
*/
?>

Features of an associative array

In general, arrays occur quite frequently in coding. An associative array goes the extra mile by keeping key-value pairs. In fact, many other programming languages use this type of data structure. One example is the dictionary in Python which is somewhat similar to associative arrays in PHP.

Here are some features of PHP’s associative arrays.

  • PHP has many built-in functions for associative arrays.
  • The keys are user-defined and mutable.
  • The keys and values could be any valid PHP data type.
  • Keys provide alot of insights about the data.
  • They are favorable for storing a JSON/XML response.

So far, we’ve seen single-dimensional associative arrays but they could be multi-dimensional as well. So, we will talk about multi-dimensional associative arrays.

Multi-dimensional associative arrays

Multi-dimensional arrays are the one that contains nested arrays. An associative array can be multi-dimensional. In fact, JSON and XML responses from APIs are parsed and decoded to associative arrays in PHP. Here, we’ll also see why multi-dimensional are favorable for representing a JSON response.

First, let’s see how to make a multi-dimensional associative array in PHP.

<?php
//A multi-dimensional associative array for employee data.
$employee_data = array(
    "Benjamin" => array("Age"=>25,"Department"=>"Marketing","Work Experience (In Years)"=>3),
    "Mark" => array("Age"=>29,"Department"=>"Finance","Work Experience (In Years)"=>5),
);
 
//Prints an array
print_r($employee_data);
 
/*
OUTPUT
Array
(
    [Benjamin] => Array
        (
            [Age] => 25
            [Department] => Marketing        
            [Work Experience (In Years)] => 3
        )
 
    [Mark] => Array
        (
            [Age] => 29
            [Department] => Finance
            [Work Experience (In Years)] => 5
        )
 
)
*/
 
?>

We’ve two employees’ data in the array. The keys are the names and the values are again associative arrays with some information about the employee. This structure can be visualized better in a tabular form.

NameAge DepartmentWork Experience (In years)
Benjamin25Marketing3
Mark29Finance5
Tabular representation of employees data

This is what we’ve in the example. Some of you might have experience with relational databases like mySQL. These databases are often seen in such tabular formats. That’s why it is convenient and insightful to fetch database responses into an associative array.

A similar example could be decoding a JSON response into an associative array. PHP has json_decode function that is often used in working with JSON or XML API responses. Let’s see a JSON and its equivalent associative array.

JSON and Associative Arrays

[
{
    id   : 1,
    Name : "Sarah",
    Age  : 30,
    Department : "Administration",
    WorkExperience : 6,
    SalaryUSD: 7000
},
{
    id   : 2,
    Name : "Mark",
    Age  : 29,
    Department : "Finance",
    WorkExperience : 5,
    SalaryUSD: 6000
},
]

JSON has the key-value pairs as well. Let’s see its equivalent associative array.

<?php
//A multi-dimensional associative array for employee data.
$employee_data = array(
    "1" => array("Name"=>"Sarah","Age"=>30,"Department"=>"Administraion","WorkExperience"=>6,"SalaryUSD"=>7000),
    "2" => array("Name"=>"Mark","Age"=>29,"Department"=>"Finance","WorkExperience"=>5,"SalaryUSD"=>6000)
);
 
//Prints an array
print_r($employee_data);
 
/*
OUTPUT
Array
(
    [1] => Array
        (
            [Name] => Sarah
            [Age] => 30
            [Department] => Administraion
            [WorkExperience] => 6        
            [SalaryUSD] => 7000
        )
 
    [2] => Array
        (
            [Name] => Mark
            [Age] => 29
            [Department] => Finance
            [WorkExperience] => 5
            [SalaryUSD] => 6000
        )
 
)
*/
?>

Both the formats are coherent, well-structured, and insightful. That’s why associative arrays are ideal for decoding JSON. The article covered more than just how to make an associative array in PHP. We always try to emphasize more on practical aspects of a topic. We hope you have enjoyed this article as well.

Want to explore further about PHP arrays?

We have many fun articles related to PHP arrays. You can explore these to learn more about arrays in PHP.

Sort an array in PHP

Print an array in PHP

Loop through an array in PHP