2. IntroductionIntroduction
An array can store one or more values in
a single variable name.
When working with PHP, sooner or later,
you might want to create many similar
variables.
Instead of having many similar variables,
you can store the data as elements in an
array.
Each element in the array has its own ID
so that it can be easily accessed.
MOHAMAD RAHIMI MOHAMAD
ROSMAN
3. Types of ArrayTypes of Array
There are three different kind of arrays:
◦ Numeric array
An array with a numeric ID key
◦ Associative array
An array where each ID key is associated with a
value
◦ Multidimensional array
An array containing one or more arrays
MOHAMAD RAHIMI MOHAMAD
ROSMAN
4. Numeric ArraysNumeric Arrays
A numeric array stores each element with
a numeric ID key.
There are different ways to create a
numeric array.
◦ Example
In this example the ID key is automatically
assigned:
$names = array(“Kamal",“Ahmad",“Ali");
MOHAMAD RAHIMI MOHAMAD
ROSMAN
5. ◦ Example 2
In this example we assign the ID key manually:
$names[0] = “Kamal";
$names[1] = “Ahmad";
$names[2] = “Ali";
MOHAMAD RAHIMI MOHAMAD
ROSMAN
Variable name value
6. ExampleExample
The ID keys can be used in a script:
MOHAMAD RAHIMI MOHAMAD
ROSMAN
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " . $names[2] .
" are ". $names[0] . "'s neighbors";
?>
What is the output of the above script?
7. Associative ArrayAssociative Array
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.
MOHAMAD RAHIMI MOHAMAD
ROSMAN
8. 1st
technique
◦ $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
2nd
technique
◦ $ages[‘Kamal'] = "32";
◦ $ages[‘Ahmad'] = "30";
◦ $ages[‘Ali'] = "34";
<?php
$ages[‘Kamal'] = "32";
$ages[‘Ahmad'] = "30";
$ages[‘Ali'] = "34";
echo “Kamal is " . $ages[‘Kamal'] . " years old.";
?>
MOHAMAD RAHIMI MOHAMAD
ROSMAN
What is the output of the above script?
11. ExerciseExercise
ID Name Class CGPA
2001 Rahul 3A 3.56
2002 Yunos 3B 3.49
2003 Mubin 3C 3.85
2004 Anuar 3D 3.63
MOHAMAD RAHIMI MOHAMAD
ROSMAN
Create four (4) array, namely:
•Id
•name
•class
•Cgpa
Then, assign those array into
the following statements:
Last week, a student named …………… , with
UiTM ID …………….., from class …………….
with a CGPA of ………….. has been choosen to
represent our university for a debate tournament