Page 116 - Open Soource Technologies 304.indd
P. 116
Unit 7: Functions
$cars[1]=”Volvo”; Notes
$cars[2]=”BMW”;
$cars[3]=”Toyota”;
Example: In the following example you access the variable values by referring to the
array name and index:
<?php
$cars[0]=”Saab”;
$cars[1]=”Volvo”;
$cars[2]=”BMW”;
$cars[3]=”Toyota”;
echo $cars[0] . “ and “ . $cars[1] . “ are Swedish cars.”;
?>
The code above will output:
Saab and Volvo are Swedish cars.
Associative Arrays
An associative array, each ID key is associated with a value. When storing data about specific
named values, a numerical array is not always the best way to do it. With associative arrays we
can use the values as keys and assign values to them.
Example: 1. In this example we use an array to assign ages to the different persons:
$ages = array(“Peter”=>32, “Quagmire”=>30, “Joe”=>34);
Example: 2. This example is the same as example 1, but shows a different way of creating
the array:
$ages[‘Peter’] = “32”;
$ages[‘Quagmire’] = “30”;
$ages[‘Joe’] = “34”;
The ID keys can be used in a script:
<?php
$ages[‘Peter’] = “32”;
$ages[‘Quagmire’] = “30”;
$ages[‘Joe’] = “34”;
echo “Peter is “ . $ages[‘Peter’] . “ years old.”;
?>
The code above will output:
Peter is 32 years old.
LOVELY PROFESSIONAL UNIVERSITY 111