php

PHP Associative Array

Mainly two types of the array can be created in any programming language. One is a numeric array and another is an associative array. Each value of an array is accessible by the index of that value. The index value is not required to define for numeric array and the sorted numeric index is generated automatically for this array if no index is defined. If it is required to create a particular string value for each index of the array, then the associative array is used to do the task.

PHP associative array can contain a number or both number and string in the index value. The user-defined index is used in an associative array. The ‘=>’ is used to assign the key-value pair of the associative array in PHP. The way to define and use associative array in PHP was shown in this tutorial.

Pre-requisite

The scripts used in the examples of this tutorial are written based on the PHP 8 version. Do the following task before executing the examples of this script.

  1. Install apache2 and PHP 8.
  2. Set execute permission for all files and folders under /var/www/html folder where all PHP files will be stored.

Example-1: One-Dimensional Associative Array

Create a PHP file with the following script to check the use of a one-dimensional associative array in PHP. In this example, an associative array of five elements has been declared where the key contains the name of the customer and the value contains the balance of the customer.

Another two elements have been added to the array after declaring the array. Next, a particular value has been printed by defining the key-value and all keys and the corresponding values of the array have been printed by using the loop.

<?php

//Declare an associative array of 5 elements

$customers = array("Arfan Niso"=>900000, "Mehjabin Chowdhury"=>780000, "Tania Bisti"=>679000, "Arifin Suvho"=>1000000, "Mossarof Korim"=>980000);

//Add two more elements

$customers["Farin Tisa"] = 500000;

$customers["Sawon Chowdhury"] = 670000;


//Print information of a particular customer

echo "<b>The particular Customer's information:</b><br/>";

echo "The balance of Mehjabin Chowdhury is: " . $customers["Mehjabin Chowdhury"]." taka.<br/>";


//Print information of all customers

echo "<br/><b>All customer's information:</b><br/>";

foreach ($customers as $key=>$val)

{

   echo "The balance of $key is $val taka.<br/>";

}

?>

Output:

The following output will appear after executing the above script. Here, the filename is array1.php and stored inside /var/www/html/code folder.

http://localhost/code/array1.php

Example-2: Two-Dimensional Associative Array

A two-dimensional array is used to store tabular data. A two-dimensional array is created in PHP by declaring an array inside another array. Create a PHP file with the following script to check the use of a two-dimensional associative array in PHP. In this example, a two-dimensional associative array of five rows and three columns has been declared.

The outer array of the script is a numeric array and the inner array of the script is an associative array that contains the product’s id, name, and price as keys. Next, the details of the particular product and all products have been printed. Here, the ‘<pre>’ tag is used to print the tab(\t) space and newline(\n) in the output using `echo`.

<?php

//Declare a two-dimensional array of 5 elements

$products = array(
array(
        "id" => "01",
        "name" => "Moniter",
        "price" => 200
    ),
array(
        "id" => "02",
        "name" => "Mouse",
        "price" => 5
    ),
array(
        "id" => "03",
        "name" => "Keyboard",
        "price" => 50
    ),
array(
        "id" => "04",
        "name" => "HDD",
        "price" => 100
    ),
array(
        "id" => "05",
        "name" => "Scanner",
        "price" => 80
    )
);

//Print the information of the first product
echo "<b>The information of the first product is :</b><br />";
echo "<b> ID: </b>".$products[0]["id"]."<br />";
echo "<b>Name: </b>".$products[0]["name"]."<br />";
echo "<b>Price: </b>"."$".$products[0]["price"]."<br />";

//Print the information of all product
echo "<br /><b>The information of all products are :</b><br /> ";
echo "<pre>ID\tName\tPrice\n";
foreach ($products as $records)
{
    foreach ($records as $val)
    {
            echo $val."\t";
    }
    echo "\n";
}


echo "</pre>";

?>

Output:

The following output will appear after executing the above script. Here, the filename is array2.php and stored inside /var/www/html/code folder.

http://localhost/code/array2.php

Example-3: Associative Array of Mixed Index

In the previous two examples, all keys of the associative array contain the string value and the values contain the mix of string and numeric value. But the key of the associative array can contain different types of value. Create a PHP file with the following script to check the use of the one-dimensional associative array of mixed index values in PHP.

In this example, an associative array of three elements has been declared where the first key contains the numeric data and the next two keys contain the string data. Next, a counter variable has used to identify each element of the array and print the formatted output based on the counter value. Each element of the array has iterated by a for loop here.

<?php

//Declare an associative array of different index type
$mix_array = array(111234=>3.89, "department"=>"EEE", "batch"=>30);

//Initialize the counter
$counter = 0;
//Iterate the array
foreach ($mix_array as $key => $val)
{
    //Print message based on the counter
    if($counter == 0)
        echo "<br />The CGPA of $key is $val<br />";
    elseif($counter == 1)
        echo "The $key name is $val<br />";
    elseif($counter == 2)
        echo "The $key no. is $val<br />";
    //Increment the counter
    $counter++;
}  


?>

Output:

The following output will appear after executing the above script. Here, the filename is array3.php and stored inside /var/www/html/code folder.

http://localhost/code/array3.php

Conclusion

The simple uses of one-dimensional and two-dimensional associative arrays in PHP have been explained in this tutorial with examples. The use of an associative array makes the script more understandable because the key or index value of the array is defined by the coder. The mixed type of index value and the element value of the array is supported in PHP because it is a weakly typed language. I hope this tutorial will help the new PHP user to use associative array properly in their script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.