Vous êtes sur la page 1sur 16

Arrays

Mohammad Homayoon Fayez


Zealand Institute of Business and Technology
Arrays
An array is a fourth type of value, which, in a special case, can be seen as
containing a sequence of values.
<?php

$towers[0] = "Sears Tower";


$towers[1] = "The Round Tower";
$towers[2] = "The Eifel Tower";
?>
Numerically indexed arrays
We index an array from 0 to N -1 where N is the number of elements in the array
Associative arrays
you can reference the items in an associative array by name rather than by
number.
Numerically indexed Arrays
Adding items to array, the following will implicitly index the array with 0 to N-1 where N = 4
<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
print_r($paper);
?>
Adding item to array using explicit locations
<?php
$paper[0] = "Copier";
$paper[1] = "Inkjet";
$paper[2] = "Laser";
$paper[3] = "Photo";
print_r($paper);
?>
Associative Arrays
you can reference the items in an array by name rather than by number.

<?php
$paper['copier'] = "Copier & Multipurpose";
$paper['inkjet'] = "Inkjet Printer";
$paper['laser'] = "Laser Printer";
$paper['photo'] = "Photographic Paper";
echo $paper['laser']; // prints Laser Printer
?>
Adding items to an array using the array keyword
<?php
//indexed 0 to 3
$p1 = array("Copier", "Inkjet", "Laser", "Photo");
echo "p1 element: " . $p1[2] . "<br>";
//Asociative
$p2 = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
echo "p2 element: " . $p2['inkjet'] . "<br>";
?>
Retrieving items from Array
For loop

<?php
$paper[0] = "Copier";
$paper[1] = "Inkjet";
$paper[2] = "Laser";
$paper[3] = "Photo";

for ($j = 0 ; $j < 4 ; ++$j) {


echo "$j: $paper[$j] <br>";
}
?>
Retrieving items from Array
Foreach loop

This is another kind of loop in php. It is specially good to use for arrays.
The process starts with the first item and ends with the last one, so you dont
even have to know how many items there are in an array
Walking through a numeric array using foreach
<?php
$paper = array("Copier", "Inkjet", "Laser", "Photo");
$j = 0;
foreach($paper as $item)
{
echo "$j: $item<br>";
++$j;
}
?>
Retrieving items from Array
Foreach loop - continued

And this is how you will use it for an associative array


<?php
$paper = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
foreach($paper as $item => $description) {
echo "$item: $description<br>";
}
?>
The displayed result of this code is as follows:
copier: Copier & Multipurpose
inkjet: Inkjet Printer
laser: Laser Printer
photo: Photographic Paper
Retrieving items from Array
An alternative

Walking through an associative array using each and list


<?php
$paper = array(
'copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper
);

while (list($item, $description) = each($paper)) {


echo "$item: $description<br>";
}
?>
Associative Arrays Example
Example photo.html: (Fix the errors)
<html><body><h2>Photo System</h2>
<form action="photo.php" method="post">
<p>Enter name: <input type="text" name="name" /></p>
<p><input type="submit" value="Search" /></p>
</form>
</body></html>
The file photo.php:
<html><body><h2> Photo System: result </h2>
<? $photo[David"] = "http://www.example.com/images/david.jpg";
$photo["Arne"] = "http://www.example.dk/pictures/bigarne.gif";
$photo["Niels"] = "http://www.example.dk/images/Niels.jpg";
if ( $photo[$name] == "" ) {
echo "No photo of $name in the Photo System!";
} else {
echo "<h3>Photo of $name</h3>
<img width=300 src=$photo[$name] />";
}
?> <p><a href="photo.html"> New Search? </a>

</body></html>
Multidimensional Arrays

<?php
'misc' => array(
$products = array(
'tape' => "Sticky Tape",
'paper' => array(
'glue' => "Adhesives",
'copier' => "Copier & Multipurpose",
'clips' => "Paperclips"
'inkjet' => "Inkjet Printer",
)
'laser' => "Laser Printer",
);
'photo' => "Photographic Paper
echo "<pre>";
),
'pens' => array(
foreach($products as $section => $items)
'ball' => "Ball Point", foreach($items as $key => $value) {
'hilite' => "Highlighters", echo "$section:\t$key\t($value)<br>";
'marker' => "Markers }
), echo "</pre>";
?>
Example: Throwing dice
The service throws a number of dice any number of times and allows us to inspect the outcome distribution.
The file dice.html:
<html>
<body><h2>Dice Throwing</h2>
<form action="dice.php" method="post">
<p>Dice per throw: <input type="text" name="dice" /><p>
<p>Number of throws: <input type="text" name="throws" /><p>
<input type="submit" value="Throw" />
</form>
</body>
</html>
The user enters the number of dice to be thrown in each throw.
The user enters the number of throws.
Plan for the file dice.php:
Construct a distribution array $dist that maps the outcome (the number of eyes in a throw) to the
number
of times this outcome is thrown.
Output the distribution array.
Throwing dice
The file dice.php: (Fix the errors)

<html><body><h2> Dice Throwing: result </h2>


<? // Initialize distribution
for ( $i=$dice ; $i <= 6*$dice ; $i=$i+1 ) {
$dist[$i] = 0;
}
for ( $t=0 ; $t < $throws ; $t=$t+1 ) { // Construct distribution
$outcome = 0;
for ( $d=0 ; $d < $dice ; $d=$d+1 ) { // Throw dice
$outcome = $outcome + rand(1,6);
}
$dist[$outcome] = $dist[$outcome] + 1; // Increase distribution
}
// Output distribution
for ( $i=$dice ; $i <= 6*$dice ; $i=$i+1 ) {
echo "$i : $dist[$i]<br />";
}
?>
</body></html>
Example: Throwing dice continued
A nicer output of the distribution using HTML tables dice2.php: (Fix the errors)
<html><body><h2> Dice Throwing 2: result </h2>
<?
...
// Find the number of occurences for the most occuring outcome
$max = 0;
for ( $i=$dice ; $i <= 6*$dice ; $i=$i+1 ) {
if ( $dist[$i] > $max ) { $max = $dist[$i]; }
}
// Output distribution
for ( $i=$dice ; $i <= 6*$dice ; $i=$i+1 ) {
$width = (100 * $dist[$i]) / $max;

echo "<table width=$width% bgcolor=red>

<tr><td>$i : $dist[$i]</td></tr>

</table>";

}
?>

</body></html>
Note: To compute the width of each table, we first compute the number of occurrences for the most occuring
outcome (eyes).
Exercise
PHP comes with numerous other functions for handling arrays. The full list is
at http://tinyurl.com/arraysinphp
Explore use and explain the following functions
is_array
count
sort
shuffle
explode
extract
compact
reset
end
sort() and count() Example
<html>
<body><h2> Towers </h2>
<ul>
<?php
$towers[0] = "Sears Tower"; // Construct array
$towers[1] = "The Round Tower";
$towers[2] = "The Eifel Tower";
sort($towers); // Sort alphabetically
for ( $i=0 ; $i < count($towers) ; $i=$i+1 )
{ // Output content
echo "<li>$towers[$i]</li> ";
}
?>
</ul>
</body></html>
The function sort sorts the array alphabetically
The function count returns the number of elements in an array