Professional Documents
Culture Documents
Contents
Unit 4: Arrays 2
Learning Objectives 2
Introduction to Array 3
Array in PHP 3
Creating an Array 3
Array Sorting 12
Summary 18
Problems to Solve 19
Unit 4: Arrays
Learning Objectives
Introduction to Array
An array is a collection of related values stored under a common name.
Examples of an array could be list of items, marks scored in each level of a game or monthly sales of a product
Array in PHP
An Array comprises of elements where each element is a key -value pair. For example price of different ice
cream flavors can be stored in an array as a key-value pair
Array
Key Value
Almond Punch 275
Nutty Crunch 160
Choco Dip 290
Oreo Cherry 250
Creating an Array
Arrays can be created using
$arrayname [key]=value
$arrayname[]=value
array() language construct
$icecream_menu['Almond Punch']=275;
$icecream_menu['Nutty Crunch']=160;
$icecream_menu['Choco Dip']=290;
$icecream_menu['Oreo Cherry']=250;
$icecream_menu[0]=275;
$icecream_menu[1]=160;
$icecream_menu[2]=290;
$icecream_menu[3]=250;
Arrays can be created with other scalar values as well as mix of them
$icecream_menu1[-1]=275;
$icecream_menu1[item 2]=160;
$icecream_menu1[3.4]=290;
$icecream_menu1[false]=250;
PHP automatically increments array key numbers when an array is created or adds elements to an array with the
empty brackets syntax
$items[]="pen";
$items[]="pencil";
$items[]='eraser';
The empty brackets add an element to the array. The elements index/key will be one more then the largest
index available in the array at that time. If the array doesn't exist yet, the empty brackets add an element with an
index/key of 0.
The Key is optional. When the Key is omitted, array is assigned a numeric key automatically starting with index 0
from the first element onwards
$icecream_menu=array(275,160,290,250);
$icecream_menu=array(0=>275,1=>160,2=>290,3=>250);
$icecream_menu=array(-1=>275,'item 2'=>160,3.4=>290,false=>250);
$marks=array();
$marks[0]=67;
$marks[1]=56.7;
$marks[]=89.5;
$arrayname[key] format
$icecream_menu['Choco Dip']=300;
Note: when attempting to modify, if an invalid key is given PHP will not throw an error. Instead it will be
considered as a new element
Since no such key called Choco dip is already available in the array, it is c onsidered as a new element and
added into the array
Therefore now the array contains 2 ice creams in the name Choco Dip and Choco dip
The count() function is used to find the number of elements in the array
Array ( [Almond Punch] => 275 [Nutty Crunch] => 160 [Choco Dip] => 290 [Oreo
Cherry] => 250 )
Syntax
The following examples print the icecream flavours and its price in a table on the web browser
<h3 align="center"><i>Chillers...</i></h3>
<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>
<?php
foreach($icecream_menu as $key=>$value)
{
print "<tr bgcolor='#F3F3F3'>";
print "<td>".$key."</td><td>".$value."</td>";
print "</tr>";
}
?>
</table>
<html>
<body>
<h3 align="center"><i>Chillers...</i></h3>
<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>
<?php
foreach($icecream_menu as $key=>$value)
{
print "<tr bgcolor='#F3F3F3'>";
print "<td>".$key."</td><td>".$value."</td>";
print "</tr>";
}
?>
</table>
<?php
foreach($icecream_menu as $key=>&$value)
{
//increase the price of all icecreams by 50
$icecream_menu[$key]=$value+50;
$value=$icecream_menu[$key];
print "<td>".$key."</td><td>".$value."</td>";
print "</tr>";
}
?>
</table>
</body>
</html>
where & can be used with $value.Any change in $value,indirectly modifies the value of the array for the current
key during the iteration. The same output as above can be achieved using the following code snippet
foreach($icecream_menu as $key=>&$value)
{
//increase the price of all icecreams by 50
$value=$value+50;
print "<td>".$key."</td><td>".$value."</td>";
print "</tr>";
}
foreach() construct when used will give the value of the array, whereas for() construct will give the position of
the array element
The following example prints the hobby of a person using foreach() construct.
foreach($hobbies as $hobby)
{
print "<br> $hobby ";
Associative arrays can also be iterated using the foreach format shown above. But the array key cannot be
accessed. Only the array value can be accessed
for($i=0,$arraysize=count($hobbies);$i<$arraysize;$i++)
print "<br> $hobbies[$i]";
unset[$array[key]]
unset($icecream_menu['Nutty Crunch']);
The Nutty Crunch element is removed from the array and the array size is decremented by 1. Therefore there
are only three flavours of ice cream instead of 4
The implode() function is used to convert the array element into a string and to use any delimiter if required
between the array elements. The implode function in the following example converts the hobbies array elements
into a string by delimiting them using a comma (,)
$games="Golf,Cricket,Tennis,Football,Hockey";
$favourite_games=explode(",",$games);
Array Sorting
sort() Function
Sorts the elements of an array in ascending order. The following code snippet sort the games in ascending order
$games=array("Golf","Cricket","Tennis","Football","Hockey");
print("<b>Before Sorting.....</b>");
foreach($games as $game)
print "<BR>".$game;
sort($games);
print "<br><br>";
print("<b>After Sorting.....</b>");
foreach($games as $game)
print "<BR>".$game;
Before Sorting.....
Golf
Cricket
Tennis
Football
Hockey
After Sorting.....
Cricket
Football
Golf
Hockey
Tennis
The sort() function should be used only for arrays with numeric index. When this function is used on Associative
array, the values are sorted in ascending order and the keys are reset to numeric index.
The following code snippet sorts the icecream_menu array in ascending order of price.
Before Sorting.....
Almond Punch 275
Nutty Crunch 160
After Sorting.....
0 160
1 250
2 275
3 290
The keys, which were strings before sorting, have been reset to numbers after sorting.
asort() function
The assort() function is used to sort an Associative Array in ascending order based on its values. The keys are
kept together with their values while sorting
The following code snippet sorts the icecream_menu array in ascending order of price.
print("<b>Before Sorting.....</b>");
foreach($icecream_menu as $flavour=> $price)
print "<BR>".$flavour." ".$price;
asort($icecream_menu);
print "<br><br>";
print("<b>After Sorting.....</b>");
foreach($icecream_menu as $flavour=>$price)
print "<BR>".$flavour." ".$price;
Before Sorting.....
Almond Punch 275
Nutty Crunch 160
Choco Dip 290
Oreo Cherry 250
After Sorting.....
Nutty Crunch 160
Oreo Cherry 250
Almond Punch 275
Choco Dip 290
ksort() function
ksort() function is used to sort an associative array in ascending order based on their keys.
The values are kept together with their keys while sorting
The following code snippet sorts the icecream_menu based on its icecream flavours
Before Sorting.....
Almond Punch 275
Nutty Crunch 160
Choco Dip 290
Oreo Cherry 250
After Sorting.....
Almond Punch 275
Choco Dip 290
Nutty Crunch 160
Oreo Cherry 250
Reverse-Sorting functions
rsort()
arsort()
krsort().
Works similar to sort(), asort() and ksort() except that they sort the array in descending order of values or keys
depending on their nature.
Multidimensional Array
Multi-dimensional arrays are arrays whose elements/values are arrays .In other words an array within an array is
called a multi-dimensional array
Instead of just icecream flavours and price, if each icecream flavour has a category (single, family, couple, treat
etc) based on which the price is decided ,it has to be implemented using a multidimensional array
$icecream_menu=array('Almond
Punch'=>array("single"=>275,"couple"=>425,"family"=>500),
'Nutty Crunch'=>array("couple"=>375,"family"=>450),
'Choco Dip'=>array("single"=>275,"Treat"=>425,"family"=>600),
'Oreo Cherry'=>array("single"=>450,"family"=>525));
foreach($favourite_games as $category=>$games)
{
print("<b>Favourite ".$category." games are ....<br></b>");
foreach($games as $game)
{
print $game."<br>";
}
}
Summary
Now that you have completed this unit, you should be able to
Problems to Solve
1. Write a function that accepts an array of numbers and sorts all even number first, all odd numbers
second in ascending order and then return the array
Example :
Input Array: 1,3,2,5,8,2,7,4,9,6,11
Output Array: 2,2,4,6,8,1,3,5,7,9,11
2. Create an array to hold 5 subject marks of a student. Calculate the grade and print the grade of the
student in the following format
Student Name:
Subject: Marks:
Maths 40
Science 60
English 90
Language 64
Moral Science 82
90-100 O
70-89 A
60-69 B
50-59 C
<50 F
3. Write a function called sortArray() that Sorts the above array in the alphabetical order of the subjects
4. Modify Exercise 1 to create an array that hold 5 subject marks of 5 students and calculate the grade and
display as mentioned in Exercise 1.
5. Create an array to maintain the population information of the country. For every country the population
count is given separately for male, female and children in crs
India(50,35,23)
Africa(67,64.5,60)
Australia(20,15,10)
China(100,80,85)
Iterate the array and print the Country names and their individual population count as follows.
The information should be displayed in the order of the country that has the highest population