This page looks plain and unstyled because you're using a non-standard compliant browser. To see it in its best form, please upgrade to a browser that supports web standard_personals. It's free and painless.

Build A Website Blog

Associative arrays in PHP Scripting

Skip | 10 November, 2005 18:43

Associative arrays are those arrays that use string values instead of numbers as the index positions.

Take for instance a shopping cart array that contains the names of the fruits and the quantities chosen. We declare such an array in this way (we’ll be using session variables — keep in mind that when you use session variables the first command in your PHP file should be session_start()):

== Code begins ==

<?php

$_SESSION[’cart’][’apples’]=20;
$_SESSION[’cart’][’oranges’]=25;
$_SESSION[’cart’][’bananas’]=60;
$_SESSION[’cart’][’peaches’]=35;

echo $_SESSION[’cart’][’oranges’];

?>

== Code ends ==

The last command in the above snippet prints 25, a value the index position “oranges” contains. Don’t worry if your find the array “cart” a bit cryptic. $_SESSION[’cart’] makes sure that the array cart is a session variable and not a normal variable so that when you fill the cart with various items and the page gets refreshed, the old values that “cart” already holds are not lost.

For the sake of example I have filled the values manually (very soon I’ll demonstrate how to fill the cart array dynamically, in real time). Looping through an associative arrays seems a bit difficult at the outset but once you’ve done it a few times, it becomes a routine. Here’s how you loop through the above array:

== Code begins ==

<?php

$_SESSION[’cart’][’apples’]=20;
$_SESSION[’cart’][’oranges’]=25;
$_SESSION[’cart’][’bananas’]=60;
$_SESSION[’cart’][’peaches’]=35;

foreach($_SESSION[’cart’] as $key => $value)
{
    print "Quantity of " . $key . " = " . $value . "<br>";
}

?>

== Code ends ==

This outputs:

Quantity of apples = 20
Quantity of oranges = 25
Quantity of bananas = 60
Quantity of peaches = 35

The foreach () loop used three things:

  1. The name of the associative array
  2. The index position [ $key ]
  3. The value that position holds

About the author - Amrit Hallan is a freelance copywriter, and a website content writer. He also dabbles with PHP and HTML. For more tips and tricks in PHP, JavaScripting, XML, CSS designing and HTML, visit his blog at  http://www.aboutwebdesigning.com

Comments for post

 
Build A Website | Javascript | HTML Help | Persuasive Copywriting | HTML Form | Simple eMail Form | Build A Website Map