Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

PHP Associative Array


PHP allows you to associate name/label with each array elements in PHP using => symbol. Such way, you can easily remember the element because each element is represented by label than an incremented number.

Definition

There are two ways to define associative array:

1st way:

  1. $salary=array(“Sonoo”=>“550000”,“Vimal”=>“250000”,“Ratan”=>“200000”);

2nd way:

  1. $salary[“Sonoo”]=“550000”;
  2. $salary[“Vimal”]=“250000”;
  3. $salary[“Ratan”]=“200000”;

Example

File: arrayassociative1.php

  1. <?php
  2. $salary=array(“Sonoo”=>“550000”,“Vimal”=>“250000”,“Ratan”=>“200000”);
  3. echo “Sonoo salary: “.$salary[“Sonoo”].“<br/>”;
  4. echo “Vimal salary: “.$salary[“Vimal”].“<br/>”;
  5. echo “Ratan salary: “.$salary[“Ratan”].“<br/>”;
  6. ?>

Output:

Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000

File: arrayassociative2.php

  1. <?php
  2. $salary[“Sonoo”]=“550000”;
  3. $salary[“Vimal”]=“250000”;
  4. $salary[“Ratan”]=“200000”;
  5. echo “Sonoo salary: “.$salary[“Sonoo”].“<br/>”;
  6. echo “Vimal salary: “.$salary[“Vimal”].“<br/>”;
  7. echo “Ratan salary: “.$salary[“Ratan”].“<br/>”;
  8. ?>

Output:

Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000

Traversing PHP Associative Array

By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.

  1. <?php
  2. $salary=array(“Sonoo”=>“550000”,“Vimal”=>“250000”,“Ratan”=>“200000”);
  3. foreach($salary as $k => $v) {
  4. echo “Key: “.$k.” Value: “.$v.“<br/>”;
  5. }
  6. ?>

Output:

Key: Sonoo Value: 550000
Key: Vimal Value: 250000
Key: Ratan Value: 200000

Comments

comments