0% found this document useful (0 votes)
19 views

(Lesson 7) Arrays

Uploaded by

aastproject10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

(Lesson 7) Arrays

Uploaded by

aastproject10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Arrays

Dr. Ali Allam Web Programming (BIS317E)


Introduction to Arrays

 An array is a special variable (object), which can hold more than one value
at a time.
 An array stores multiple values in one single object.
 In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index

 Associative arrays - Arrays with named keys

 Multidimensional arrays - Arrays containing one or more arrays


Introduction to Arrays

 To introduce the importance of arrays, let’s discuss the following example:


▪ Suppose you have a list of names (e.g. employees’ names). Storing their names in
different separate variables would look like this:
$name1 = “Ahmed Mostafa”;
$name2 = “Sarah Maged”;
$name3 = “Youssef Farid”;
 Oops! … what if you want to loop through the employees and find a
certain one? and what if you have100 employees? Of course it’s
unrealistic to define 100 different variables!
 Solution … The solution is to create an array. An array can hold many
values with one single name, and you can access the values by referring to
an index number in that array.
Indexed Arrays:
Array with a numeric index
Indexed Arrays

 The index of an array refers to the location of an item within the array.
 The index always start from 0.
 So, an array of 100 items, has an index starting from 0 to 99.
 The indices can be assigned automatically, like this:
$names = array("Ahmed", "Sarah", "Youssef"); → Array containing three strings
$grades = array(87, 95, 68, 94, 25, 76); → Array containing six integers
 The indices can also be assigned manually, like this:
$names[0] = "Ahmed";
$names[1] = "Sarah";
$names[2] = "Youssef";
Example: defining and assigning values to an array

The following example creates an indexed array called $names, assigns three
elements to it, and then prints a message containing the array values:
<html>
<body>
<?php
$names = array("Ahmed", "Sarah", "Youssef");
echo "<h3>Employees:</h3><ol>
<li>$names[0]</li> <li>$names[1]</li>
<li>$names[2]</li></ol>";
?>
</body>
</html>

 Tip: ARRAYS should be typically handled via LOOPS. Let’s see how …
Handling an array using “for” loop

Printing the elements of an array using a for-loop:


<html>
<body>
<?php
$names = array("Ahmed", "Sarah", "Youssef");
echo "<h3>Employees:</h3><ol>";
for($i=0; $i<=2; $i++)
{
echo "<li> $names[$i]</li>";
}
echo"</ol>";
?>
</body>
</html>

 Looping is the typical way to deal with an array, no matter how big it is.
Handling an array using “while” and “do while”

Of course, we can also print the elements of an array using “while” and “do while” loops:
<html> <html>
<body> <body>
<?php <?php
$names = array("Ali", "Mai", "Adel", "John", "Mary"); $names = array("Ali", "Mai", "Adel", "John", "Mary");
echo "<h3>Employees:</h3><ol>"; echo "<h3>Employees:</h3><ol>";
$i=0; $i=0;
while($i<=4) do
{ {
echo "<li> $names[$i]</li>"; echo "<li> $names[$i]</li>";
$i++; $i++;
} } while($i<=4);
echo"</ol>"; echo"</ol>";
?> ?>
</body> </body>
</html> </html>
Handling an array using “foreach” loop

Printing the elements of an array using “foreach” loop:


<html>
<body>  “foreach” is a special kind of
<?php
$names = array("Ali", "Mai", "Adel", "John", "Mary");
loops which is heavily used with
echo "<h3>Employees:</h3><ol>"; arrays (i.e. it works only on
foreach($names as $x)
{
arrays, and nothing else).
echo "<li> $x</li>";
}
 The striking advantage of using
echo"</ol>"; “foreach” loop, is that it surpasses
?>
</body> the hassle of the array’s indexing.
</html>
Example: Input the values
 All previous examples assigned fixed values to an array, like this:
$names = array("Ahmed", "Sarah", "Youssef");
 What if the user is asked to enter the employees’ names through a form, and then the
program gets them printed out.
<html>
<body><h3>Enter the employees names:</h3>
<form action="index.php" method="get">
<table>
<tr><td>Employee (1):</td><td><input type="text" name="emp[ ]"></td></tr>
<tr><td>Employee (2):</td><td><input type="text" name="emp[ ]"></td></tr>
<tr><td>Employee (3):</td><td><input type="text" name="emp[ ]"></td></tr>
<tr><td><input type="submit"></td><td><input type="reset"></td></tr>
</table>
</form>
</body>
</html>
Example: Print the entered values

PHP Program (index.php)


<html>
<body>
<?php
$names = $_GET["emp"];
echo "<h3>Employees:</h3><ol>";
foreach($names as $x)
{
echo "<li> $x</li>";
}
echo"</ol>";
?>
</body>
</html>
Indexed Arrays: dynamic size

 Let’s go for more dynamicity and flexibility… Suppose that we want to


define an array of an undetermined size in which the user is asked to enter
its size.
 For example, the user is first asked to enter the number of employees.
Accordingly, the user is redirected to a form to enter their names. At the
end, the program prints the names of these employees.
Example: Enter the number of elements in the array

Input form (form1.html):


Enter Number of Employees
<html>
<body>
<form action="form2.php">
Number of Employees:
<input type="text" name="num"> &nbsp;
<input type ="submit">
</form>
</body>
</html>
Example: Enter the values of the array

Input form (form2.php): Enter Employees’ Names


<html>
<body>
<form action="index.php"><table>
<?php
$num = $_GET["num"];
for($i=1; $i<=$num; $i++)
{
echo"<tr><td>Employee ($i)</td>
<td><input type=text name=emp[]></td></tr>";
}
?>
<tr><td><input type="submit" value="Print Info"></td></tr>
</table></form>
</body>
</html>
Example: Print all the values of the array

PHP program (index.php)


<html>
<body>
<h3> Employees:</h3>
<ol>
<?php
$employees = $_GET["emp"];
foreach($employees as $value)
{
echo "<li>$value</li>";
}
?>
</ol>
</body>
</html>
Indexed Arrays: More examples

 In the previous part, you’ve been introduced to the concept of defining


arrays, inputting and outputting their values.
 Now, let’s take more examples to emphasize the importance of using
arrays. Examples, such as:
➢ Filtering the values of an array
➢ Calculating the average of the values of an array
➢ Getting the highest value in an array
Example: Filtering the values of an array
 The user inputs ten values into an array. The program prints the positive ones only.
<html> <html>
<body> <body>
<form action= "example1.php"> <table> <b>The positive values are:</b><br>
<?php <?php
for($i=1; $i<=10; $i++) $Arr = $_GET["num"];
echo "<tr><td>Value ($i)</td> for($i=0; $i<=9; $i++)
<td><input type=text name=num[]></td></tr>"; {
?> if($Arr[$i]>0)
<tr><td></td> echo "$Arr[$i]<br>";
<td><input type=submit value=Print Positive Values></td></tr> }
</table> </form> ?>
</body> </body>
</html> </html>

Input form (form1.php) PHP Program (example1.php)


Example: Filtering the values of an array
Example: Calculating the average

 The user inputs ten values. The program calculates and prints their average.
<html> <html>
<body> <body>
<form action= "example2.php"> <table> <?php
<?php $Arr = $_GET["num"];
for($i=1; $i<=10; $i++) $sum = 0;
echo "<tr><td>Grade ($i)</td> foreach($Arr as $val)
<td><input type=text name=num[]></td></tr>"; {
?> $sum = $sum + $val;
<tr><td></td> }
<td><input type= "submit" value= "Get Average"></td></tr> $avg = $sum / 10;
</table> </form> echo "<h3>The average is $avg</h3>";
</body> ?>
</html> </body>
</html>
Input form (form2.php) PHP Program (example2.php)
Example: Calculating the average
Example (1): Adding up two different arrays

<html>
<body>
<form action= "total.php">
<table><tr><th>Student ID</th><th>Exam1</th>
<th>Exam2</th></tr>
<?php
for($i=1; $i<=5; $i++)
echo "<tr><td>Student ($i)</td>
<td><input type=text name=exam1[]></td>
<td><input type=text name=exam2[]></td></tr>";
?>
<tr><td><input type= "submit" value= "Calculate
Total"></td></tr>
</table> </form>
</body>
</html>
Input form (form1.php)
Example (1): Adding up two different arrays

<html>
<body>
<table border=1 cellspacing=0><tr><th>Exam1</th>
<th>Exam2</th><th>Total</th></tr>
<?php
$exam1 = $_GET["exam1"];
$exam2 = $_GET["exam2"];
for($i=0; $i<=4; $i++)
{
$total[$i] = $exam1[$i] + $exam2[$i];
echo"<tr><td>$exam1[$i]</td><td>$exam2[$i]
</td> <td>$total[$i]</td></tr>";
}
?>
</body>
</html>
PHP Program (total.php)
Example (2): Getting the maximum value

 The program gets the highest value of ten inputs.


<html>
<body>
<form action= "maximum.php">
<table>
<?php
for($i=1; $i<=10; $i++)
echo "<tr><td>Grade ($i)</td>
<td><input type=text name=num[]></td></tr>";
?>
<tr><td></td>
<td><input type= "submit" value= "Get Maximum"></td></tr>
</table> </form>
</body>
</html>
Input form (form2.php)
Example (2): Getting the maximum value

<html>
<body>
<?php
$Arr = $_GET["num"];
$max = $Arr[0];
foreach($Arr as $val)
{
if($val>$max)
$max = $val;
}
echo "<h3>The highest grade is $max</h3>";
?>
</body>
</html>

PHP Program (maximum.php)


Handling checkboxes and list boxes

 Arrays are also used to handle multi-


valued data entries, such as data entered
via checkboxes and list boxes.
 All values of a given multi-valued entry
(e.g. languages and interests) are stored
within an array.
Example of handling checkboxes and list boxes

<html> <body> <h3>Personal Data:</h3> <form action="index.php"> <table>


<tr><td>Full Name</td><td><input type="text" name="fullname"></td></tr>
<tr><td>Languages</td>
<td><input type="checkbox" name="lang[ ]" value="Arabic">Arabic
<input type="checkbox" name="lang[ ]" value="English">English
<input type="checkbox" name="lang[ ]" value="French">French</td></tr>
<tr><td>Interests</td>
<td><select name="hobby[ ]" multiple size="5">
<option value="Sports">Sports</option>
<option value="Reading">Reading</option>
<option value="Fishing">Fishing</option>
<option value="Camping">Camping</option>
<option value="Traveling">Traveling</option></select></td></tr>
<tr><td><input type="submit" value="Print Info"></td>
<td><input type="reset"></td></tr>
</table></form></body></html>
Input form (form3.php)
Example (3): Handling checkboxes and list boxes
(using foreach loop)
<html><body>
<?php
$name = $_GET["fullname"];
$lang = $_GET["lang"];
$hobby = $_GET["hobby"];
echo"<p><b>Name:</b> $name</p> <p><b>Languages: </b></p>";
echo"<ul>";
foreach($lang as $val)
{ echo"<li>$val</li>"; }
echo"</ul>";
echo"<p><b>Interests: </b></p>";
echo"<ul>";
foreach($hobby as $val)
{ echo"<li>$val</li>"; }
echo"</ul>";
?>
</body></html>
PHP Program (index.php)
Example of handling checkboxes and list boxes
(using for loop)
<html><body>
<?php
$name = $_GET["fullname"];
$lang = $_GET["lang"];
$hobby = $_GET["hobby"];
echo"<p><b>Name:</b> $name</p> <p><b>Languages: </b></p>";
echo"<ul>";
for($i=0; $i<count($lang); $i++)
{ echo"<li>$lang[$i]</li>"; }
echo"</ul>";
echo"<p><b>Interests: </b></p>";
echo"<ul>";
for($i=0; $i<count($hobby); $i++)
{ echo"<li>$hobby[$i]</li>"; }
echo"</ul>";
?>
</body></html>
PHP Program (index.php)
Self-Study
Built-in functions of arrays
 The array functions are part of the PHP core (i.e. built-in/language-
defined). These functions allow you to access and manipulate arrays.
 Here are some of these functions. You’ve already learned some of them:
Function Description Example
array ( ) Creates an array and assigns its values $marks = array(4, 7, 5, 3, 6);
count ( ) Returns the number of elements in an array $num = count($marks);
sort ( ) Sorts an array in an ascending order sort($marks);
rsort ( ) Sorts an array in a descending order rsort($marks);
shuffle ( ) Shuffles an array (mix it up) shuffle($marks)
array_reverse ( ) Returns an array in the reverse order $mark2 = array_reverse($marks);
array_search ( ) Searches for a value and returns its index $ind = array_search(5,$marks);
Array’s Functions: sort / rsort

<html><body>
<?php
$name = array("Bassem", "Dina", "Ahmed", "Carol");
$mark = array(76, 93, 65, 97, 55, 82, 42);
sort($name);
rsort($mark);
echo "<h3>Sorted Names: (ascending):</h3><ol>";
for($i=0; $i<count($name); $i++)
echo"<li>$name[$i]</li>";
echo"</ol>";
echo"<h3>Sorted Numbers (descending):</h3> <ol>";
foreach($mark as $x)
echo"<li>$x</li>";
echo"</ol>";
?>
</body></html>
Array’s Functions: shuffle
<html>
<body>
<?php
$name = array("Bassem", "Dina", "Ahmed", "Carol");
shuffle($name);
echo "<h3>Names shuffled randomly:</h3><ul>";
foreach($name as $val)
echo"<li>$val</li>";
echo"</ul>";
shuffle($name);
echo "<h3>Names shuffled again:</h3><ul>";
foreach($name as $val)
echo"<li>$val</li>";
echo"</ul>";
?>
</body>
</html>
Search, read, and learn more about:
array_reverse()
array_search()
array_sum()

You might also like