April 21, 2016
Associative Arrays in PHP
Associative arrays are object-indexed collection of items. They are also known as key-value pairs where index act as key and its item act as value. A simple array is used when you want to create collection of items and you want to store them in a certain order. An associative array is used when you want to store items based on their key or a label. This can be better understood with an example where you have a bunch of boxes with a label on them like shoe, dress, socks etc. Each box contains items depending upon its label which will make easy for everyone to pick an item from right box. Like simple array, you can also add more items to an associative array. Example is given below.
<?php $array= array("Robert" => "Manager", "Andrea" =>"Secretary", "Sam" => "Boss", "Peter" => "Assistant", "Rony" => "HR" ); //Printing array items. echo print_r($array). "<br />" ; //Getting a value by its key. echo $array["Rony"] . "<br />"; //Adding an item to array. $array["Mark"] = "Peon"; //Getting a value by its key. echo $array["Mark"]; ?>