Press "Enter" to skip to content

Understanding Associative Array in PHP Programming

This tutorial provides basic information and examples regarding how to use associative arrays in PHP programming language.

What is an Associative Array in PHP?

Associative Array in PHP is an array with a string index where each value can be assigned a specific key instead of linear storage. It can also be used to store multiple values at the same time. When we retrieve data from a database, data will be returned as an associative array.

How to Create an Associative Array in PHP?

An associative array can be created using two ways in PHP programming language.

(i) We can create an Associative Array by using an array() function.

What is the syntax for creating an Associative array in PHP using the first process?

$array_variable=array("key_name1"=>"value1","key_name2"=>"value2","key_name3"=>"value3",....);

Example:

$a=array("name"=>"shinu","address"=>"kolkata","salary="=>"90000");

(ii) We can also create an Associative array in PHP using the second process as:

Syntax:

$array_variable['key_name1']=value1;
$array_variable['key_name2']=value2;
$array_variable['key_name3']=value3;

Example:

$a['name']="shinu";
$a['address']="kolkata";
$a['salary']="90000";

How to Access The Value for an Array Element of an Associative Array?

In PHP when we want to access the value for an array element, we will use the array variable name with string index.

Now we will give an example for accessing value for an array element.

<html>
<body>
<?php
$a=array("name"=>"shinu","address"=>"kolkata","salary"=>"90000");
echo $a['name'];
?>
</body>
</html>

Output: shinu

Here the array $a is containing three elements. These are given below:

$a['name']="shinu", $a['address']="kolkata", $a['salary']="90000".

This program is returning the value of first array element with string index “name”.

How to Print an Associative Array in PHP?

There is a predefined function print_r()in PHP, which is used to print the array.

Now we will give an example for printing an Array:

<html>
<body>
<?php
$a=array("name"=>"shinu","address"=>"kolkata","salary"=>"90000");
print_r($a);
?>
</body>
</html>

Output: Array ( [name] => shinu [address] => kolkata [salary] => 90000 )

Here print_r()is returning the keys(here name,address,salary) with values(here “shinu”,”kolkata”,”90000″).