Arrays in PHP
Arrays in PHP
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
hard, boring, and bad idea to store
• green
each color in a separate variable
• blue
• balck
• white
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");
• 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 2
$colorList = array("apple"=>"red", $colorList["apple"] = "red";
"grass"=>"green", $colorList["grass"] = "green";
"sky"=>"blue", $colorList["sky"] = "blue";
"night"=>"black", $colorList["night"] = "black";
"wall"=>"white"); $colorList["wall"] = "white";
3
$colorList["apple"] = "red"; As you can see even the numbers can
$colorList[5] = "green"; be any so you don't have to make it
$colorList["sky"] = "blue"; continous. However be aware of using
$colorList["night"] = "black"; such mixed arrays as it can result
$colorList[22] = "white"; errors.