You are on page 1of 19

Course Handout Student Notebook

Contents
Unit 4: Arrays 2

Learning Objectives 2

Introduction to Array 3

Array in PHP 3

Creating an Array 3

Accessing Elements of an A rray 5

Modifying Elements of an Array 6

Finding the Size of an Array 6

Printing an Array in a readable way 6

Iterating Array Elements 7

Modifying Array while iteration 8

Iterating Array with Numeric index 11

Removing an element from an Array 11

Converting an Array to String 12

Converting String to an Array 12

Array Sorting 12

Accessing elements of a Multidimensional Array 16

Iterating Multidimensional Array 16

Summary 18

Problems to Solve 19

Copyright IBM Corp. 2011 Course Contents 1


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
PHP Core Student Notebook

Unit 4: Arrays
Learning Objectives

At the end of this unit, you will be able to


Understand what is an array
Know various ways to create ,access and modify the elements of an array
Understand how to iterate an array and modify the elements while iteration
Use various functions to sort an array
Create and manipulate multidimensional array

Copyright IBM Corp. 2011 Unit 4 PHP Basics 2


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

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

Key has to be unique within an array. But Values can repeat.


A particular ice cream flavor can occur only once in the array. Almond Punch cannot be repeated in the array
with same/different price. But two different ice cream flavors can have the same price. Therefore Almond
Punch and Choco Dip can have the same price.
An array key has to be only a scalar value (String, Number, Boolean); whereas value of an array can be both
scalar (String, Number, Boolean) and non-scalar (array and other values).
PHP interpreter treats arrays with numeric keys and arrays with string keys (and arrays with a mix of both)
identically. Generally arrays with only numeric keys are referred as "numeric," "indexed," or "ordere d" arrays,
and with string-keyed as "associative" arrays. In other words, an array whose keys are something other than the
positions of the values within the array is called an Associative array.

Creating an Array
Arrays can be created using
$arrayname [key]=value
$arrayname[]=value
array() language construct

Array creation using $arrayname [key]=value

To create the ice cream menu array

$icecream_menu['Almond Punch']=275;

3 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

$icecream_menu['Nutty Crunch']=160;
$icecream_menu['Choco Dip']=290;
$icecream_menu['Oreo Cherry']=250;

To create an array with Numeric key

$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;

Creating array with [ ]

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';

echo $items[1]; //output: pencil

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.

Creating Array using array() construct

Arrays are generally created using array() construct

array([key =>] value, [key =>] value, ...)

The following creates an ice cream menu array

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco


Dip'=>290,'Oreo Cherry'=>250);

Copyright IBM Corp. 2011 Unit 4 PHP Basics 4


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

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

The following creates an array with numeric index

$icecream_menu=array(275,160,290,250);

which is equivalent to the following array creation

$icecream_menu=array(0=>275,1=>160,2=>290,3=>250);

An array with a mix of all values can also be created

$icecream_menu=array(-1=>275,'item 2'=>160,3.4=>290,false=>250);

Creating an Empty Array

$marks=array();

The following assigns values to the mark array

$marks[0]=67;
$marks[1]=56.7;
$marks[]=89.5;

Accessing Elements of an Array

Array elements can be accessed using

$arrayname[key] format

For the array

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco


Dip'=>290,'Oreo Cherry'=>250);

To access the price of Choco Dip ice cream

print $icecream_menu['Choco Dip']; //output: 290

To access the element of the marks array

print $marks[1] ; // output:56.7

5 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Modifying Elements of an Array

To Modify the price of Choco Dip ice cream

$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

To modify the price of Choco Dip ice cream

icecream_menu[Choco dip']=300; //d is given in Lowercase instead of


Uppercase

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

Finding the Size of an Array

The count() function is used to find the number of elements in the array

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco


Dip'=>290,'Oreo Cherry'=>250);
print "There are ".count($icecream_menu) ." flavours of icecreams
available!!"

prints the following

There are 4 flavours of icecreams available!!

Printing an Array in a readable way


The print_r() ,when passed an array, prints its contents in a readable way.
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco
Dip'=>290,'Oreo Cherry'=>250);
print_r($icecream_menu);

Copyright IBM Corp. 2011 Unit 4 PHP Basics 6


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Output of the above code will be

Array ( [Almond Punch] => 275 [Nutty Crunch] => 160 [Choco Dip] => 290 [Oreo
Cherry] => 250 )

Iterating Array Elements


The easiest way to iterate through each element of an array is with foreach(). The foreach()construct executes
the block of code once for each element in an array.

Syntax

foreach($array as [$key =>] [&] $value)


{
//block of code to be executed for each iteration
}

$array represents the array to be iterated


$key is optional, and when specified, it contains the currently iterated array values key, which can be any scalar
value, depending on the keys type.
$value holds the array value, for the given $key value.
Using the & for the $value, indicates that any change made in the $value variable while iteration will be
reflected in the original array($array) also.

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

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco


Dip'=>290,'Oreo Cherry'=>250);

foreach($icecream_menu as $key=>$value)
{
print "<tr bgcolor='#F3F3F3'>";

7 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

print "<td>".$key."</td><td>".$value."</td>";
print "</tr>";
}

?>
</table>

Output on the Web Browser

Modifying Array while iteration


Arrays can be modified during iteration in 2 ways.
Direct Array Modification
Indirect Array Modification

Direct Array Modification


Say for example we need to increase the price of the all icecreams by 50 .The following code helps us to update
the price and display the revised price along with the old ones

<html>
<body>
<h3 align="center"><i>Chillers...</i></h3>
<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>

Copyright IBM Corp. 2011 Unit 4 PHP Basics 8


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

<?php

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco


Dip'=>290,'Oreo Cherry'=>250);

foreach($icecream_menu as $key=>$value)
{
print "<tr bgcolor='#F3F3F3'>";

print "<td>".$key."</td><td>".$value."</td>";

print "</tr>";
}

?>
</table>

<h3 align="center"><i>Chillers Revised Price.....</i></h3>


<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>

<?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 "<tr bgcolor='#F3F3F3'>";

print "<td>".$key."</td><td>".$value."</td>";

print "</tr>";
}

?>
</table>
</body>
</html>

9 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Indirect Array Modification

Recollect the foreach syntax

foreach($array as [$key =>] [&] $value)


{
//block of code to be executed for each iteration
}

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 "<tr bgcolor='#F3F3F3'>";

print "<td>".$key."</td><td>".$value."</td>";

print "</tr>";
}

Copyright IBM Corp. 2011 Unit 4 PHP Basics 10


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Iterating Array with Numeric index

Arrays with numeric index can be accessed using


foreach()
for()

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.

$hobbies=array("Reading Books","Playing Golf","Watching Tennis","Dancing");

print "<b>My Hobbies Are...</b>";

foreach($hobbies as $hobby)
{
print "<br> $hobby ";

The output of the following code on the Web Browser will be


My Hobbies Are...
Reading Books
Playing Golf
Watching Tennis
Dancing

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

The same output can be achieved using for() construct as follows

for($i=0,$arraysize=count($hobbies);$i<$arraysize;$i++)
print "<br> $hobbies[$i]";

Removing an element from an Array

The unset function is used to remove an element from the array

unset[$array[key]]

To remove Nutty Crunch from the icecream menu card

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

11 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Converting an Array to String

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 (,)

$hobbies=array("Reading Books,Playing Golf,Watching Tennis","Dancing");


$hobby="My Hobbies are ".implode(",",$hobbies);
echo $hobby;

Will display the output as

My Hobbies are Reading Books,Playing Golf,Watching Tennis,Dancing

Converting String to an Array


The explode function is used to convert a string into an array. The following code converts games string into a
favourite_games array by using explode();

$games="Golf,Cricket,Tennis,Football,Hockey";
$favourite_games=explode(",",$games);

echo "My second favorite game is ".$favourite_games[1];

displays the output as

My second favourite game is Cricket

Array Sorting

Functions that are used to sort an array in particular order are


sort()
asort()
ksort()
rsort()
arsort()
krsort()

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;

Copyright IBM Corp. 2011 Unit 4 PHP Basics 12


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

sort($games);
print "<br><br>";
print("<b>After Sorting.....</b>");
foreach($games as $game)
print "<BR>".$game;

Output of the above code in web browser is

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.

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco


Dip'=>290,'Oreo Cherry'=>250);
print("<b>Before Sorting.....</b>");
foreach($icecream_menu as $flavour=> $price)
print "<BR>".$flavour." ".$price;
sort($icecream_menu);
print "<br><br>";
print("<b>After Sorting.....</b>");
foreach($icecream_menu as $flavour=>$price)
print "<BR>".$flavour." ".$price;

will display the output as

Before Sorting.....
Almond Punch 275
Nutty Crunch 160

13 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Choco Dip 290


Oreo Cherry 250

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.

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco


Dip'=>290,'Oreo Cherry'=>250);

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;

will display the output as

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.

Copyright IBM Corp. 2011 Unit 4 PHP Basics 14


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

The values are kept together with their keys while sorting

The following code snippet sorts the icecream_menu based on its icecream flavours

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo


Cherry'=>250);
print("<b>Before Sorting.....</b>");
foreach($icecream_menu as $flavour=> $price)
print "<BR>".$flavour." ".$price;
ksort($icecream_menu);
print "<br><br>";
print("<b>After Sorting.....</b>");
foreach($icecream_menu as $flavour=>$price)
print "<BR>".$flavour." ".$price;

will display the output as

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),

15 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

'Choco Dip'=>array("single"=>275,"Treat"=>425,"family"=>600),
'Oreo Cherry'=>array("single"=>450,"family"=>525));

Examples of some Multidimensional arrays would be

$favourite_games=array("indoor"=>array("Carom","Cards","Snook er"),"out door"=>array("Cricket","Football","Hoc


key"));
$ordered_items=array(array("Ballotine of Salmon","Potage of Wild SeaBass" ,"Truffles"),array("Poulet Bresse
'Cassoulet'", "Fillet of Venison","Monkfish Wrapped in Green Chilly,Fillet of Aromatic Angus Steak"));

Accessing elements of a Multidimensional Array


echo "Almond Crunch, Couple Package Costs $".$icecream_menu['Almond
Punch']['couple']."<br>";
echo "My First Favourite Outdoor Game is
".$favourite_games['outdoor']['0']."<br>";
echo "The First Starter Dish Expected is ".$ordered_items[0][0]."<br>";

will display the output as

Almond Crunch, Couple Package Costs $425


My First Favourite Outdoor Game is Cricket
The First Starter Dish Expected is Ballotine of Salmon

Iterating Multidimensional Array


$favourite_games=array("indoor"=>array("Carom","Cards","Snooker"),"outdoor"=>
array("Cricket","Football","Hockey"));

The following code snippet iterates the favourite_games array

foreach($favourite_games as $category=>$games)
{
print("<b>Favourite ".$category." games are ....<br></b>");
foreach($games as $game)
{
print $game."<br>";
}
}

The output will be displayed as follows

Copyright IBM Corp. 2011 Unit 4 PHP Basics 16


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Favourite indoor games are ....


Carom
Cards
Snooker
Favourite outdoor games are ....
Cricket
Football
Hockey

17 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Summary

Now that you have completed this unit, you should be able to

Understand what is an array


Know various ways to create ,access and modify the elements of an array
Understand how to iterate an array and modify the elements while iteration
Use various functions to sort an array
Create and manipulate multidimensional array

Copyright IBM Corp. 2011 Unit 4 PHP Basics 18


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

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

Total: Average: Grade:

The grade is calculated as follows:

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.

Country Male Female Children

The information should be displayed in the order of the country that has the highest population

19 PHP Copyright IBM Corp.2011

You might also like