Associative Array in PHP | Syntax | Creation | Examples

Hello Friend how are you i hope you all are doing well. Today in this post we will learn about Associative Array in PHP like what is Associative  Array, Syntax of  Associative  Array, Initialization of Associative  Array with examples. If you want to learn PHP in very simple easy way then this post will help you definitely.

Associative Array in PHP

1.It is a type of array in which each element of array is associated with key.
2.In associative array there are two elements key and Value.
3.array() function is used to create array in PHP.
4.There are two method of creating Associative array.

First Method:

<?php
$salary=array("Rocky"=>35000,"Raj"=>50000,"Tony"=>45000,"Ronny"=>87000);
?>

Second Method:

<?php
$salary['Rocky'] = "35000";
$salary['Raj'] = "50000";
$salary['Tony'] = "45000";
$salary['Ronny'] = "87000";
?>

Access/Print Element of Associative Array

There are two way of printing element of Associative Array in PHP

Printing of associative array element method 1:

 
<?php
$salary=array("Rocky"=>35000,"Raj"=>50000,"Tony"=>45000,"Ronny"=>87000);

echo "Salary of Rocky is ".$salary['Rocky']."<br>";
echo "Salary of Raj is ".$salary['Raj']."<br>";
echo "Salary of Tony is ".$salary['Tony']."<br>";
echo "Salary of Ronny is ".$salary['Ronny']."<br>";
/*
OUTPUT
Salary of Rocky is 35000
Salary of Raj is 50000
Salary of Tony is 45000
Salary of Ronny is 87000
*/
?>

Printing of associative array element method using loop:

 
<?php
$salary=array("Rocky"=>35000,"Raj"=>50000,"Tony"=>45000,"Ronny"=>87000);
foreach($salary as $k=>$v)
{
  echo $k."'s Salary is ".$v."<br>";
}
/*
OUTPUT
Rocky's Salary is 35000
Raj's Salary is 50000
Tony's Salary is 45000
Ronny's Salary is 87000
*/
?>

Types of Array in PHP

There are three types of Array in PHP
1.Indexed Array Click here to learn.
2.Associative Array Click here to learn.
3.Multi Dimension Array Click here to learn.

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 

If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

Thanks

Post a Comment

0 Comments