Lecture -5
Arrays
1
Arrays in PHP
• To create a new array variable in PHP uses array() or using square brackets ([])
• PHP support two types of arrays:
1. Index arrays- each element is referenced by a numeric index, usually
starting from zero.
e.g $authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens”);
e.g echo $authors[0];
2. Associative arrays- is also referred to as a hash or map. With associative
arrays, each element is referenced by each element is specified by a key-value
pair.
e.g $myBook = array( “title” = > “The Grapes of Wrath”, “author” = >
“John Steinbeck”, “pubYear” = > 1939 );
Faculty of Information Science 2
Arrays in PHP (Cont’d)
• "title", "author", and "pubYear" are keys.
• "The Grapes of Wrath", "John Steinbeck", and 1939 are the corresponding
values.
• You can access elements in an associative array using their keys.
echo $myBook["title"];
Faculty of Information Science 3
Accessing Array Elements
Example
• $authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$pos = 2;
echo $authors[$pos + 1]; // Displays “Dickens”
• $authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authors[2] = “Melvill //["Steinbeck", "Kafka", "Melville", "Dickens"].
• $authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authors[] = “Orwell”;//add a new element to the end of the
array
Faculty of Information Science 4
Outputting an Entire Array with print_r()
< html xmlns=”[Link] xml:lang=”en” lang=”en” >
< head >
< title > Outputting Arrays with print_r() < /title >
< link rel=”stylesheet” type=”text/css” href=”[Link]” / >
< /head >
< body >
< h1 > Outputting Arrays with print_r() < /h1 >
< ?php
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
echo ‘ < h2 > $authors: < /h2 > < pre > ’;
print_r ( $authors );
echo ‘ < /pre > < h2 > $myBook: < /h2 > < pre > ’;
print_r ( $myBook );
echo “ < /pre > ”;
?> Faculty of Information Science 5
< /body > < /html >
Extracting a Range of Elements with array_slice() and
count with count()
• array_slice() that you can use to extract a range of elements from an
array.
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authorsSlice = array_slice( $authors, 1, 2 );
print_r( $authorsSlice );// Displays Array ( [0] => Kafka [1] =>
Tolkien )
count() returns the number of elements as an integer:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
echo count( $authors );// Displays “4”
Faculty of Information Science 6
Stepping Through an Array
Faculty of Information Science 7
Stepping Through an Array(Cont’d)
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“[Link] >
< html xmlns=”[Link] xml:lang=”en”
lang=”en” >
< head >
< title > Stepping Through an Array < /title >
< link rel=”stylesheet” type=”text/css” href=”[Link]” / >
< /head >
< body >
< h1 > Stepping Through an Array < /h1 >
< ?php
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
echo “ < p > The array: “ . print_r( $authors, true ) . “ < /p > ”;
echo “ < p > The current element is: “ . current( $authors ) . “. < /p > ”;
echo “ < p > The next element is: “ . next( $authors ) . “. < /p > ”;
echo “ < p > ...and its index is: “ . key( $authors ) . “. < /p > ”;
echo “ < p > The next element is: “ . next( $authors ) . “. < /p > ”;
echo “ < p > The previous element is: “ . prev( $authors ) . “. < /p > ”;
echo “ < p > The first element is: “ . reset( $authors ) . “. < /p > ”;
echo “ < p > The last element is: “ . end( $authors ) . “. < /p > ”;
echo “ < p > The previous element is: “ . prev( $authors ) . “. < /p Faculty
> ”; of Information Science 8
? > < /body > < /html >
Using for each to Loop Through
Values
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
foreach ( $authors as $val ) {
echo $val . “ < br/ > ”;
}
Output:
Steinbeck
Kafka
Tolkien
Dickens
Faculty of Information Science 9
Using foreach to Loop Through
Keys and Values
< body >
< h1 > Using foreach < /h1 >
< dl >
< ?php
$myBook = array( “title” = > “The Grapes of Wrath”, “author” = > “John
Steinbeck”, “pubYear” = > 1939 );
foreach ( $myBook as $key = > $value ) {
echo “ < dt > $key < /dt > ”;
echo “ < dd > $value < /dd > ”;
}
?>
< /dl >
< /body >
< /html >
Faculty of Information Science 10
<?php
$myBooks = array(
Working with Multidimensional Arrays
array(
"title" => "The Grapes of Wrath",
"author" => "John Steinbeck",
"pubYear" => 1939
),
array(
"title" => "The Trial",
"author" => "Franz Kafka",
“pubYear” => 1925
),
array(
"title" => "The Hobbit",
"author"=> "J. R. R. Tolkien",
“pubYear" => 1937
),
);
echo "<pre>";
print_r ( $myBooks ); Faculty of Information Science 11
////Create an associative array containing the age of Peter, Ben and Joe.
-- assign Peter is 35, Ben is 37 and Joe is 43 and displaying the ages of Peter, Ben and Joe.
Use the correct array method to sort the $colors array alphabetically.
$colors = array("red", "green", "blue", "yellow");
Hint: Use sort() Function
Use the correct array method to sort the $colors array descending alphabetically.
$colors = array("red", "green", "blue", "yellow");
Hint: rsort() Function
Use the correct array method to sort the $age array according to the values.
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Hint: values in ascending order asort() Function
Faculty of Information Science 12
Try It Out
• Create a PHP page ([Link]) that creates an array ($a) to
store the following information of 3 persons by static array()
statement, then display the content of $a on the page by using
print_r function. Note that James Bond does not have any family
member, but “Family member” must appear in the array as a
“key”.
Faculty of Information Science 13
Exercise ([Link])
<?php
$a= array(
array('Name'=>"Mickey Mouse",
'Age'=>80,
'Nationality'=>"USA”,
'Family member'=>array('Girl friend')),
array('Name'=>"Yoichi Kogure”,
'Age'=> 49,
'Nationality'=>"Japan”,
’Family member'=>array('Wife’,'Daughter’,'Son')),
array('Name'=>"James Bond",
'Age'=>100,
'Nationality'=>"England",
'Family member'=>array())
);
echo "<pre>";
print_r ($a);
echo "</pre>";
Faculty of Information Science 14
?>
Try It Out
• Suppose we receive the array ($a) in question 1 as a result from external
program, so that the content (such as number of persons, name, number
of family members, etc.) will change from time to time (i.e. variable). Now,
create a PHP page ([Link]) and copy all the PHP code from
[Link]. Then, add PHP code that programmatically creates
another array ($b) (not by static array() statement) that has the following
format of information from the give array ($a).
Faculty of Information Science 15
Exercise ([Link])
<?php
$a= array(
array('Name'=>"Mickey Mouse",
'Age'=>80, 'Nationality'=>"USA",
'Family member'=>array(0=>'Girl friend')),
array('Name'=>"Yoichi Kogure",'Age'=> 49,
'Nationality'=>"Japan",'Family
member'=>array(0=>'Wife',1=>'Daughter',2=>'Son')),
array('Name'=>"James Bond",'Age'=> 100,
'Nationality'=>"England",'Family member'=>array())
);
foreach($a as $key => $value) {
$b[$key]["Name"]=$a[$key]["Name"];
$b[$key]['Number of family
members']=count($a[$key]['Family member']);
}
echo "<pre>"; print_r ($b);
Faculty of Information Science 16
echo "</pre>"; ?>
Sorting Arrays
•sort($array): Sorts an array in ascending order (numerically or alphabetically).
•rsort($array): Sorts an array in descending order.
• asort()and arsort() – For sorting associative arrays
• ksort()and krsort()– For sorting associative arrays by key rather
than by value
• array_multisort()– A powerful function that can sort multiple
arrays at once, or multidimensional arrays
Faculty of Information Science 17
Sorting Arrays (Examples)
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
sort( $authors );
print_r( $authors );
// Displays “Array ( [0] = > Dickens [1] = > Kafka [2] = > Steinbeck [3] = >
Tolkien )”
rsort( $authors );
print_r( $authors );
// Displays “Array ( [0] = > Tolkien [1] = > Steinbeck [2] = > Kafka [3] = >
Dickens )”
Faculty of Information Science 18
Sorting Arrays(Example)
$myBook = array(“title”=> “Bleak House”,“author”=> “Dickens”,“year” = > 1853 );
asort( $myBook );
print_r( $myBook );
// Displays “Array ( [title] = > Bleak House [author] = > Dickens [year] = > 1853 )”
arsort( $myBook );
print_r( $myBook );
// Displays “Array ( [year] = > 1853 [author] = > Dickens [title] = > Bleak House )”
$myBook = array( “title” = > “Bleak House”,“author” = > “Dickens”,“year” = > 1853 );
ksort( $myBook );
print_r( $myBook );
// Displays “Array ( [author] = > Dickens [title] = > Bleak House [year] = > 1853 )”
Faculty of Information Science 19
Sorting Arrays (Example)
krsort( $myBook );
print_r( $myBook );
// Displays “Array ( [year] = > 1853 [title] = > Bleak House [author] =
> Dickens )”
• array_multisort() lets you sort multiple related arrays at the same
time
• array_multisort() sorts a two-dimensional array.
• array_multisort( $array1, $array2, ... );
Faculty of Information Science 20
Multi- sort (Example)
<?php
array(
$myBooks = array( "title" => "A Tale of Two Cities",
array( "author" => "Charles Dickens",
"title" => "The Grapes of Wrath", "pubYear" => 1859
),
"author" => "John Steinbeck",
);
"pubYear" => 1939 array_multisort( $myBooks );
), echo "<pre>";
array( print_r( $myBooks );
echo "</pre>";
"title" => "Travels With Charley",
"author" => "John Steinbeck", ?>
"pubYear" => 1962
),
array(
"title" => "The Trial",
"author" => "Franz Kafka",
"pubYear" => 1925
),
array( Faculty of Information Science 21
"title" => "The Hobbit",
Adding and Removing Array Elements
• array_unshift() – Adds one or more new elements to the start of
an array
• array_shift()– Removes the first element from the start of an
array
• array_push()— Adds one or more new elements to the end of an
array
• array_pop()— Removes the last element from the end of an
array
• array_splice()— Removes element(s) from and/or adds
element(s) to any point in an array
Faculty of Information Science 22
Adding and Removing Array Elements
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
echo array_unshift( $authors, “Hardy”, “Melville” ) . “ < br/ > ”; // Displays “6”
print_r( $authors ); // Displays “Array ( [0] = > Hardy [1] = > Melville [2] = > Steinbeck
[3] = >Kafka [4] = > Tolkien [5] = > Dickens )”
$myBook = array( “title” = > “The Grapes of Wrath”,“author” = > “John
Steinbeck”,“pubYear” = > 1939 );
echo array_shift( $myBook ) . “ < br/ > ”; // Displays “The Grapes of Wrath”
print_r( $myBook ); // Displays “Array ( [author] = > John Steinbeck [pubYear] = >
1939 )”
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
echo array_push( $authors, “Hardy”, “Melville” ) . “ < br/ > ”; // Displays “6”
print_r( $authors ); // Displays “Array ( [0] = > Steinbeck [1] = > Kafka [2] = > Tolkien
[3] = > Dickens [4] = > Hardy [5] = > Melville )”
Faculty of Information Science 23
Adding and Removing Array Elements
$myBook = array( “title” = > “The Grapes of Wrath”,“author” = > “John
Steinbeck”,“pubYear” = > 1939 );
echo array_pop( $myBook ) . “ < br/ > ”; // Displays “1939”
print_r( $myBook ); // Displays “Array ( [title] = > The Grapes of Wrath
[author] = > John Steinbeck )”
$authors = array( "Steinbeck", "Kafka", "Tolkien" );
array_splice( $authors, 1,0, array("authorName" => "Milton")); ;
print_r($authors); //Display Array ( [0] => Steinbeck [1] => Milton [2] => Kafka
[3] => Tolkien )
Faculty of Information Science 24
Merging Arrays Together
$authors = array( “Steinbeck”, “Kafka” );
$moreAuthors = array( “Tolkien”, “Milton” );
print_r( array_merge( $authors, $moreAuthors ) ); // Displays “Array ( [0] = >
Steinbeck [1] = > Kafka [2] = > Tolkien [3] = > Milton )”
$authors = array( “Steinbeck”, “Kafka” );
$moreAuthors = array( “Tolkien”, “Milton” );
array_push( $authors, $moreAuthors );
print_r( $authors ); // Displays “Array ( [0] = > Steinbeck [1] = > Kafka [2] = >
Array ( [0] = > Tolkien [1] = > Milton ) )”
$myBook = array( “title” = > “The Grapes of Wrath”,“author” = > “John
Steinbeck”,“pubYear” = > 1939 );
$myBook = array_merge( $myBook, array( “numPages” = > 464 ) );
print_r ( $myBook ); // Displays “Array ( [title] = > The Grapes of Wrath [author]
= > John
Steinbeck [pubYear] = > 1939 [numPages] = > 464
Faculty of Information Science 25
Converting Between Arrays and Strings
• To convert a string to an array, PHP uses explode()string function.
<?php
$fruitString = "apple,pear,banana,strawberry,peach";
$fruitArray = explode( ",", $fruitString );
echo $fruitArray[0]."<br>"; // apple
echo $fruitArray[4]; //peach
?>
• To convert an array to a string, PHP uses implode()string function
$fruitArray = array( “apple”, “pear”, “banana”, “strawberry”, “peach” );
$fruitString = implode( “,”, $fruitArray );
echo $fruitString; // Displays “apple,pear,banana,strawberry,peach”
Faculty of Information Science 26
Converting an Array to a List of Variables
$myBook = array( “The Grapes of Wrath”, “John Steinbeck”, 1939 );
list( $title, $author, $pubYear ) = $myBook;
echo $title . “< br/ >”; // Displays “The Grapes of Wrath”
echo $author . “ < br/ > ”; // Displays “John Steinbeck”
echo $pubYear . “ < br/ > ”; // Displays “1939”
Faculty of Information Science 27
Exercises
1. Instead of containing author names as strings, the $booksarray contains
numeric indices (keyed on “ authorId “ ) pointing to the respective elements of
the $authors array. Write a script to add an “ authorName ” element to each
associative array within the $books array that contains the author name string
pulled from the $authors array. Display the resulting $books array in a Web
page.
2. Imagine you are writing a version of the computer game Minesweeper. Use
arrays to create and store a minefield on a 20 x 20 grid. Place ten mines
randomly on the grid, then display the grid, using asterisks (*) for the mines and
periods (.) for the empty squares. (Hint: To return a random number between 0
and 19 inclusive, use rand( 0, 19 ).)
Faculty of Information Science 28
Assignment
(1) Write PHP code that receives the values of rows and cols and
outputs a HTML table depending upon the received values ( rows and
cols ).
(2) Below is a part of directory structure in Linux server. Create a PHP
page that creates an array ($c) to store this structure. You should also
show the content of the array by using print_r function.
Faculty of Information Science 29