Associative array in php

Associative array

Associative array is defined with strings between square backets for indexing. We can define with php array function or directly.

Defining associative array with array() function:

<?php
$arr=array("first_name"=>"Peter","last_name"=>"Jackson","age"=>"25");

?>

Here "first_name" is key or index of array $arr and "Peter" is its value.

Defining associative array without array() function:

we can direcly define associative array by assigning a value to each key in square backet.

<?php
$arr["first_name"]="Peter"; 

$arr["last_name"]="Jackson";

$arr["age"]="25";

?>


The above way is also used for adding more elements to the array.

<?php
$arr["occupation"]="Engineer";

?>
For accessing any element of array, we just use key in square bracket as given below:
<?php
print $arr["first_name"]; // Peter

print $arr["last_name"];//Jackson

print $arr["age"];//25

print $arr["occupation"];//Engineer;

?>
Or for getting print of all values at once, we can use foreach loop, see as in an example.
<?php
 foreach($arr as $key=>$val)
 {
  print $val."<br/>"; 
 }
 ?>