Chapter 11
Chapter 11
Chapter 11
How to create
and use arrays
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 1
Objectives
Applied
1. Use any of the functions and techniques presented in this chapter as
you use arrays, associative arrays, and arrays of arrays.
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 2
Objectives (continued)
Knowledge
1. Distinguish between an array and an associative array, including
the difference in the way indexes are used.
2. Explain how gaps can be introduced into an array and how the
gaps can be removed.
3. Describe the use of a for loop with an array and the use of a
foreach loop with an associative array.
4. Distinguish between a queue and a stack.
5. Describe the use of the functions for creating arrays, working with
queues and stacks, performing mathematical calculations,
searching arrays, sorting arrays, and modifying arrays.
6. Distinguish between a regular array and an array of arrays,
including the difference in the number of indexes that are used to
access an element.
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 3
The syntax for creating an array
$array_name = array([value1[, value2, ... ]])
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 4
How to create an array of discounts
With one statement
$discounts = array(0, 5, 10, 15);
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 5
The syntax for adding an element to an array
$array_name[] = $value;
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 6
Functions for removing the values from elements
unset($var1[, $var2 ...])
array_values($array)
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 7
Functions for loops that work with arrays
count($array) //The number of elements in an array not
counting gaps.
end($array) //Move pointer to the last element
key($array) //The index of the element that the pointer
is on
isset($var)
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 9
An associative array is one that uses strings for
its index values. These are often called keys.
The syntax for creating an associative array
array([key1 => value1, key2 => value2, ... ])
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 10
How to create an associative array of codes
With one statement
$country_codes =
array('DEU' => 'Germany',
'JPN' => 'Japan',
'ARG' => 'Argentina',
'USA' => 'United States');
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 11
How to create an associative array of extensions
$ext = array();
$ext[10] = 'Sales';
$ext[13] = 'Customer Service';
$ext[16] = 'Returns';
$ext[18] = 'Warehouse';
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 12
How to set a value with a specific key
$name = array('first' => 'Ray', 'last' => 'Harris');
$name['middle'] = 'Thomas';
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 13
The syntax of a foreach loop
foreach ($array_name as [ $key => ] $value) {
// Statements that use $key and $value
}
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 14
A foreach loop that displays the keys and values
$tax_rates = array('NC' => 7.75, 'CA' => 8.25,
'NY' => 8.875);
echo '<ul>';
foreach ($tax_rates as $state => $rate) {
echo "<li>$state ($rate)</li>";
}
echo '</ul>';
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 15
A foreach loop that displays the values
in a regular array
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
unset($numbers[2], $numbers[6]);
$numbers_string = '';
foreach($numbers as $number) {
$numbers_string .= $number . ' ';
}
echo $numbers_string; // Displays: 1 2 4 5 6 8 9 10
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 16
How to use the range function to create an array
$numbers = range(1, 4); // 1, 2, 3, 4
$numbers = range(10, 22, 4); // 10, 14, 18, 22
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 17
How to use the array_sum function
$prices = array(141.95, 212.95, 411, 10.95);
$sum = array_sum($prices); // 776.85
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 18
How to use functions to search an array
$tax_rates = array('NC' => 7.75,
'CA' => 8.25, 'NY' => 8.875);
$is_found = in_array(7.75, $tax_rates); // TRUE
$is_found = in_array('7.75', $tax_rates); // TRUE
$is_found = in_array('7.75', $tax_rates, true);
$key_exists = array_key_exists('CA', $tax_rates);
$key = array_search(7.75, $tax_rates); // 'NC'
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 19
How to count the number of occurrences
of a value in an array
$names = array('Mike', 'Mike', 'Mike',
'Anne', 'Joel', 'Joel');
$occurences = array_count_values($names );
echo $occurences['Mike']; // 3
echo $occurences['Anne']; // 1
echo $occurences['Joel']; // 2
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 20
How to sort strings in ascending order
$names = array('Mike', 'Anne', 'Joel', 'Ray', 'Pren');
sort($names); // Anne, Joel, Mike, Pren, Ray
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 21
Examples for study
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 22
How to shuffle and deal a deck of cards
// Create the deck of cards
$faces = array('2', '3', '4', '5', '6', '7', '8',
'9', 'T', 'J', 'Q', 'K', 'A');
$suits = array('h', 'd', 'c', 's');
$cards = array();
foreach($faces as $face) {
foreach($suits as $suit) {
$cards[] = $face . $suit;
}
}
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 23
A simple array
[0] [1] [2] [3] [4]
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 24
A rectangular array of arrays
[0] [1] [2] [3] [4]
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 25
A jagged array of arrays
[‘Mike’] [‘Joel’] [‘Ray’]
[1] [1]
[2]
‘Tom Clancy’
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 26
Code that creates an array of arrays
$times_table = array();
for ($i = 0; $i <= 12; $i++) { // add 13 elements that
$times_table[$i] = array(); // contain empty arrays
}
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 27
Code that creates a cart array
$cart = array();
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 28
Referring to the elements in the array of arrays
echo $cart[0]["itemCode"]; // displays 123
echo $cart[1]["itemName"]; // displays C++ 2010
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 29
The Task List Manager application
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 30
The index.php file
<?php
if (isset($_POST['tasklist'])) {
$task_list = $_POST['tasklist'];
} else {
$task_list = array();
}
$errors = array();
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 31
The index.php file (continued)
switch( $_POST['action'] ) {
case 'add':
$new_task = $_POST['newtask'];
if (empty($new_task)) {
$errors[] = 'The new task cannot be empty.';
} else {
$task_list[] = $new_task;
}
break;
case 'delete':
$task_index = $_POST['taskid'];
unset($task_list[$task_index]);
$task_list = array_values($task_list);
break;
}
include('task_list.php');
?>
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 32
The task_list.php file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Task List Manager</title>
<link rel="stylesheet" type="text/css"
href="main.css"/>
</head>
<body>
<div id="page">
<div id="header">
<h1>Task List Manager</h1>
</div>
<div id="main">
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 33
The task_list.php file (continued)
<!-- part 1: the errors -->
<?php if (count($errors) > 0) : ?>
<h2>Errors</h2>
<ul>
<?php foreach($errors as $error) : ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 34
The task_list.php file (continued)
<!-- part 3: the add form -->
<h2>Add Task</h2>
<form action="." method="post" >
<?php foreach( $task_list as $task ) : ?>
<input type="hidden" name="tasklist[]"
value="<?php echo $task; ?>"/>
<?php endforeach; ?>
<input type="hidden" name="action" value="add"/>
<label>Task:</label>
<input type="text" name="newtask"
id="newtask"/><br />
<label> </label>
<input type="submit" value="Add Task"/><br />
</form>
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 35
The task_list.php file (continued)
<!-- part 4: the delete form -->
<?php if (count($task_list) > 0) : ?>
<h2>Delete Task</h2>
<form action="." method="post" >
<?php foreach( $task_list as $task ) : ?>
<input type="hidden" name="tasklist[]"
value="<?php echo $task; ?>"/>
<?php endforeach; ?>
<input type="hidden" name="action" value="delete"/>
<label>Task:</label>
<select name="taskid">
<?php foreach( $task_list as $id => $task ) : ?>
<option value="<?php echo $id; ?>">
<?php echo $task; ?>
</option>
<?php endforeach; ?>
</select><br />
<label> </label>
<input type="submit" value="Delete Task"/>
</form>
<?php endif; ?>
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 36
The task_list.php file (continued)
</div><!-- end main -->
</div><!-- end page -->
</body>
</html>
Murach's PHP and MySQL, C11 © 2010, Mike Murach & Associates, Inc. Slide 37