You are on page 1of 11

F5224 WEB PROGRAMMING

ARRAYS IN PHP

WHAT IS AN ARRAY ?
A variable is a storage area holding a number or text. The problem is, a variable will hold only one value. An array is a special variable, which can store multiple values in one single variable.

WHAT IS AN ARRAY ?
Example : You want to store basic colors in your PHP scripts
Color list: red green blue balck white

hard, boring, and bad idea to store each color in a separate variable

CREATING AN ARRAY
There are more ways to create an array in PHP. Types of array :
1) Numeric Array 2) Associative Array 3) Multidimensional Array

NUMERIC ARRAY
A numeric array stores each array element with a numeric index. There are two methods to create a numeric array. a) In the following example the index are automatically assigned (the index starts at 0):
$colorList = array("red","green","blue","black","white");

b) In the following example we assign the index manually: $colorList[0] = "red";


$colorList[1] = "green"; $colorList[2] = "blue"; $colorList[3] = "black"; $colorList[4] = "white";

DISPLAY THE ARRAY CONTENT


Display only one element:
echo $colorList[0];

Display all elements in array:


for ($i=0;$i<=4;$i++){ echo $colorList[$i]; }

Use a foreach loop


foreach ($colorList as $value) { echo $value; }

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.

HOW TO DECLARE
1 $colorList = array("apple"=>"red", "grass"=>"green", "sky"=>"blue", "night"=>"black", "wall"=>"white"); 2 $colorList["apple"] = "red"; $colorList["grass"] = "green"; $colorList["sky"] = "blue"; $colorList["night"] = "black"; $colorList["wall"] = "white";

$colorList["apple"] = "red"; $colorList[5] = "green"; $colorList["sky"] = "blue"; $colorList["night"] = "black"; $colorList[22] = "white";

As you can see even the numbers can be any so you don't have to make it continous. However be aware of using such mixed arrays as it can result errors. echo "The sky is ".$colorList["sky"] ." and the grass is ".$colorList["grass"];

DISPLAY THE ARRAY CONTENT

MULTIDIMENSIONAL ARRAYS
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

HOW TO DECLARE
$myLists['colors'] = array ( "apple"=>"red", "grass"=>"green", "sky"=>"blue", "night"=>"black", "wall"=>"white"); "BMW"=>"M6", "Mercedes"=>"E 270 CDI", "Lexus"=>"IS 220d", "Mazda"=>"6", "Toyota"=>"Avensis");

$myLists['cars'] = array (

echo $myLists['cars']['Toyota'];

DISPLAY THE ARRAY CONTENT

THE END

You might also like