Associative arrays in PHP
Copyright © 2005-2006 Amrit Hallan
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: the name of the associative array, the
index position [ $key ] and the value that position holds.
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
<< -------------- End of Free Reprint Article ----------- >>
Find More Free Articles
See Also:
All
Free Articles About SEO & Search Engines
All Free Articles About Web Pages & Web Design
Index of All Free Reprint Articles