An array is a special variable, which can store multiple values in one single variable.
Numeric array – an array with a numeric index.
“Two methods of to create a numeric array”
1. The index are automatically assigned (the index starts at 0).
$cellphone(“Nokia”,”Samsung”,”Ericson”,”Motorola”);
2. The index assigned manually.
$cellphone[0]=”Nokia”;
$cellphone[1]=”Samsung”;
$cellphone[2]=”Ericson”;
$cellphone[3]=”Motorola”;
Sample code:
<?php
$cellphone[0]=”Nokia”;
$cellphone[1]=”Samsung”;
$cellphone[2]=”Ericson”;
$cellphone[3]=”Motorola”;
echo $cellphone[0].”and”.$cellphone[1].”are my favorites.”;
?>
Output:
Nokia and Samsung are my favorites.
Associative array – each ID key is associated with a value.
Example 1:
In this example we use an array to assign grades to the different students:
$grades=array(“Alison=>95″,”James=>90″,”Andrae=>89″);
Example 2:
The same as example 1, but shows a different way of creating the array.
$grades[‘Alison’]=”95″;
$grades[‘James’]=”90″;
$grades[‘Andrae’]=”89″);
Sample code:
<?php
$grades[‘Alison’]=”95″;
$grades[‘James’]=”90″;
$grades[‘Andrae’]=”89″);
echo”Alison got”.$grades[‘Alison’].”points.”;
?>
Output:
Alison got 95 points.
Multidimensional array – each element in the main array can also be an array.
Example 1:
In this example we create a multidimensional array, with automatically assigned ID keys.
$families=array
(
“Lee”=>array
(
“Johnglenn”,
“Jackson”,
“Joswell”
),
“Cruz”=>array
(
“Kevin”,
“Reinheart”
),
“Smith”=>array
(
“Anne”
)
);
The array above would look like this if written to the output:
Array
(
[Lee]=>Array
(
[0]=>Johnglenn
[1]=>Jackson
[2]=>Joswell
)
[Cruz]=>Array
(
[0]=>Kevin
[1]=>Reinheart
)
[Smith]=>Array
(
[0]=>Anne
)
)
Example 2:
Try displaying a single value from the array above:
echo “Is”.$families[‘Smith’][0].”a part of the Lee family?”;
Output:
Is Anne a part of the Lee family?
Recent Comments