SlideShare a Scribd company logo
Chapter 6
Manipulating Arrays
PHP Programming with MySQL
2nd
Edition
2PHP Programming with MySQL, 2nd Edition
Objectives
In this chapter, you will:
• Manipulate array elements
• Declare and initialize associative arrays
• Iterate through an array
• Find and extract elements and values
• Sort, combine, and compare arrays
• Understand multidimensional arrays
• Use arrays in Web forms
3PHP Programming with MySQL, 2nd Edition
Manipulating Elements
if (isset($_POST['submit'])) {
$Subject = stripslashes($_POST['subject']);
$Name = stripslashes($_POST['name']);
$Message = stripslashes($_POST['message']);
// Replace any '~' characters with '-' characters
$Subject = str_replace("~", "-", $Subject);
$Name = str_replace("~", "-", $Name);
$Message = str_replace("~", "-", $Message);
$MessageRecord = "$Subject~$Name~$Messagen";
$MessageFile = fopen("MessageBoard/messages.txt", "ab");
if ($MessageFile === FALSE)
echo "There was an error saving your message!n";
else {
fwrite($MessageFile, $MessageRecord);
fclose($MessageFile);
echo "Your message has been saved.n";
}
}
4PHP Programming with MySQL, 2nd Edition
Manipulating Elements (continued)
<h1>Post New Message</h1>
<hr />
<form action="PostMessage.php" method="POST">
<strong>Subject:</strong> <input type="text" name="subject" />
<strong>Name:</strong> <input type="text" name="name" /><br />
<textarea name="message" rows="6" cols="80"></textarea><br />
<input type="submit" name="submit" value="Post Message" />
<input type="reset" name="reset" value="Reset Form" />
</form>
<hr />
<a href="MessageBoard.php">View Messages</a>
5PHP Programming with MySQL, 2nd Edition
Manipulating Elements (continued)
Figure 6-1 Post New Message page of the Message Board
Manipulating Elements (continued)
<h1>Message Board</h1>
<?php
?>
<p>
<a href="PostMessage.php">Post New Message</a>
</p>
if ((!file_exists("MessageBoard/messages.txt")) ||
(filesize("MessageBoard/messages.txt") == 0))
echo "<p>There are no messages posted.</p>n";
}
else {
$MessageArray = file("MessageBoard/messages.txt");
echo "<table style="background-color:lightgray"
border="1" width="100%">n";
$count = count($MessageArray);
6PHP Programming with MySQL, 2nd Edition
Manipulating Elements (continued)
for ($i = 0; $i < $count; ++$i) {
$CurrMsg = explode("~", $MessageArray[$i]);
echo " <tr>n";
echo " <td width="5%"
align="center"><strong>" . ($i + 1) .
"</strong></td>n";
echo " <td
width="95%"><strong>Subject:</strong> " .
htmlentities($CurrMsg[0]) . "<br />";
echo "<strong>Name:</strong> " .
htmlentities($CurrMsg[1]) . "<br />";
echo "<u><strong>Message</strong></u><br />" .
htmlentities($CurrMsg[2]) . "</td>n";
echo " </tr>n";
}
echo "</table>n";
7PHP Programming with MySQL, 2nd Edition
8PHP Programming with MySQL, 2nd Edition
Manipulating Elements (continued)
Figure 6-2 Message Board page of the Message Board
9PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
from the Beginning of an Array
• The array_shift() function removes the first
element from the beginning of an array
– Pass the name of the array whose first element
you want to remove
• The array_unshift() function adds one or
more elements to the beginning of an array
– Pass the name of an array followed by comma-
separated values for each element you want to
add
10PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements from
the Beginning of an Array (continued)
$TopSellers = array(
"Chevrolet Impala",
"Chevrolet Malibu",
"Chevrolet Silverado",
"Ford F-Series",
"Toyota Camry",
"Toyota Corolla",
"Nissan Altima",
"Honda Accord",
"Honda Civic",
"Dodge Ram");
array_shift($TopSellers);
array_unshift($TopSellers, "Honda CR-V");
echo "<pre>n";
print_r($TopSellers);
echo "</pre>n";
11PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements from
the Beginning of an Array (continued)
Figure 6-3 Output of an array modified with the array_shift()
and array_unshift() functions
12PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
from the End of an Array
• The array_pop() function removes the last
element from the end of an array
– Pass the name of the array whose last
element you want to remove
• The array_push() function adds one or more
elements to the end of an array
– Pass the name of an array followed by
comma-separated values for each element
you want to add
13PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements from
the End of an Array (continued)
$HospitalDepts = array(
"Anesthesia",
"Molecular Biology",
"Neurology",
"Pediatrics");
array_pop($HospitalDepts); // Removes "Pediatrics"
array_push($HospitalDepts, "Psychiatry", "Pulmonary
Diseases");
14PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
Within an Array
• The array_splice() function adds or
removes array elements
• The array_splice() function renumbers the
indexes in the array
• The syntax for the array_splice() function
is:
array_splice(array_name, start,
characters_to_delete, values_to_insert);
15PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
Within an Array (continued)
• To add an element within an array, include a
value of 0 as the third argument of the
array_splice() function
$HospitalDepts = array(
"Anesthesia", // first element (0)
"Molecular Biology", // second element (1)
"Neurology", // third element (2)
"Pediatrics"); // fourth element (3)
array_splice($HospitalDepts, 3, 0, "Ophthalmology");
16PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
Within an Array (continued)
• To add more than one element within an array,
pass the array() construct as the fourth
argument of the array_splice() function
• Separate the new element values by commas
$HospitalDepts = array(
"Anesthesia", // first element (0)
"Molecular Biology", // second element (1)
"Neurology", // third element (2)
"Pediatrics"); // fourth element (3)
array_splice($HospitalDepts, 3, 0, array("Opthalmology",
"Otolaryngology"));
17PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
Within an Array (continued)
• Delete array elements by omitting the fourth
argument from the array_splice() function
$HospitalDepts = array(
"Anesthesia", // first element (0)
"Molecular Biology", // second element (1)
"Neurology", // third element (2)
"Pediatrics"); // fourth element (3)
array_splice($HospitalDepts, 1, 2);
18PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
Within an Array (continued)
• The unset() function removes array elements
and other variables
• Pass to the unset() function the array name
and index number of the element you want to
remove
• To remove multiple elements, separate each
index name and element number with commas
unset($HospitalDepts[1], $HospitalDepts[2]);
19PHP Programming with MySQL, 2nd Edition
Removing Duplicate Elements
• The array_unique() function removes
duplicate elements from an array
• Pass to the array_unique() function the
name of the array from which you want to
remove duplicate elements
• The array_values() and array_unique()
functions do not operate directly on an array
• The array_unique() function does renumber
the indexes after removing duplicate values in
an array
20PHP Programming with MySQL, 2nd Edition
Removing Duplicate Elements
(continued)
$TopSellers = array(
"Ford F-Series", "Chevrolet Silverado", "Toyota Camry",
"Honda Accord", "Toyota Corolla", "Ford F-Series", "Honda
Civic",
"Honda CR-V", "Honda Accord", "Nissan Altima", "Toyota
Camry",
"Chevrolet Impala", "Dodge Ram", "Honda CR-V");
echo "<p>The 2008 top selling vehicles are:</p><p>";
$TopSellers = array_unique($TopSellers);
$TopSellers = array_values($TopSellers);
for ($i=0; $i<count($ TopSellers); ++$i) {
echo "{$TopSellers[$i]}<br />";
}
echo "</p>";
21PHP Programming with MySQL, 2nd Edition
Removing Duplicate Elements
(continued)
Figure 6-4 Output of an array after removing duplicate values
with the array_unique() function
22PHP Programming with MySQL, 2nd Edition
Declaring and Initializing
Associative Arrays
• With associative arrays, you specify an
element’s key by using the array operator (=>)
– The syntax for declaring and initializing an
associative array is:
$array_name = array(key=>value, ...);
Figure 6-5 Output of array with associative and indexed elements
23PHP Programming with MySQL, 2nd Edition
Declaring and Initializing
Associative Arrays (continued)
$Territories[100] = "Nunavut";
$Territories[] = "Northwest Territories";
$Territories[] = "Yukon Territory";
echo "<pre>n";
print_r($Territories);
echo "</pre>n";
echo '<p>The $Territories array consists of ',
count($Territories), " elements.</p>n";
Figure 6-6 Output of an array with a starting index of 100
24PHP Programming with MySQL, 2nd Edition
Iterating Through an Array
• The internal array pointer refers to the
currently selected element in an array
25PHP Programming with MySQL, 2nd Edition
Iterating Through an Array
(continued)
Figure 6-8 Output of an array without advancing the internal
array pointer
26PHP Programming with MySQL, 2nd Edition
Finding and Extracting Elements
and Values
• One of the most basic methods for finding a value
in an array is to use a looping statement to iterate
through the array until you find the value
• Rather than write custom code to find a value,
use the in_array() and array_search()
functions to determine whether a value exists in
an array
27PHP Programming with MySQL, 2nd Edition
Determining if a Value Exists
• The in_array() function returns a Boolean
value of true if a given value exists in an array
• The array_search() function determines
whether a given value exists in an array and:
– Returns the index or key of the first matching
element if the value exists, or
– Returns FALSE if the value does not exist
if (in_array("Neurology", $HospitalDepts))
echo "<p>The hospital has a Neurology
department.</p>";
28PHP Programming with MySQL, 2nd Edition
Determining if a Key Exists
• The array_key_exists() function
determines whether a given index or key exists
• You pass two arguments to the
array_key_exists() function:
– The first argument represents the key to
search for
– The second argument represents the name
of the array in which to search
29PHP Programming with MySQL, 2nd Edition
Determining if a Key Exists
(continued)
$ScreenNames["Dancer"] = "Daryl";
$ScreenNames["Fat Man"] = "Dennis";
$ScreenNames["Assassin"] = "Jennifer";
if (array_key_exists("Fat Man", $ScreenNames))
echo "<p>{$ScreenNames['Fat Man']} is already
'Fat Man'.</p>n";
else {
$ScreenNames["Fat Man"] = "Don";
echo "<p>{$ScreenNames['Fat Man']} is now
'Fat Man'.</p>";
}
30PHP Programming with MySQL, 2nd Edition
Returning a Portion of an Array
• The array_slice() function returns a portion
of an array and assigns it to another array
• The syntax for the array_slice() function is:
array_slice(array_name, start, characters_to_return);
31PHP Programming with MySQL, 2nd Edition
Returning a Portion of an Array
(continued)
// This array is ordered by sales, high to low.
$TopSellers = array("Ford F-Series", "Chevrolet Silverado",
"Toyota Camry", "Honda Accord", "Toyota Corolla", "Honda
Civic", "Nissan Altima", "Chevrolet Impala", "Dodge Ram",
"Honda CR-V");
$FiveTopSellers = array_slice($TopSellers, 0, 5);
echo "<p>The five best-selling vehicles for 2008
are:</p>n";
for ($i=0; $i<count($FiveTopSellers); ++$i) {
echo "{$FiveTopSellers[$i]}<br />n";
}
32PHP Programming with MySQL, 2nd Edition
Returning a Portion of an Array
(continued)
Figure 6-11 Output of an array returned with the
array_slice() function
33PHP Programming with MySQL, 2nd Edition
Sorting Arrays
• The most commonly used array sorting
functions are:
– sort() and rsort() for indexed arrays
– ksort() and krsort() for associative arrays
34PHP Programming with MySQL, 2nd Edition
Sorting Arrays (continued)
35PHP Programming with MySQL, 2nd Edition
Sorting Arrays (continued)
36PHP Programming with MySQL, 2nd Edition
Sorting Arrays (continued)
• If the sort() and rsort() functions are used
on an associative array, the keys are replaced
with indexes
37PHP Programming with MySQL, 2nd Edition
Sorting Arrays (continued)
Figure 6-12 Output of an array after applying the sort() and rsort() functions
38PHP Programming with MySQL, 2nd Edition
Sorting Arrays (continued)
Figure 6-13 Output of an associative array after sorting with the sort() function
39PHP Programming with MySQL, 2nd Edition
Sorting Arrays (continued)
Figure 6-14 Output of an associative array after sorting
with the asort() function
40PHP Programming with MySQL, 2nd Edition
Sorting Arrays (continued)
Figure 6-15 Output of an associative array
after sorting with the ksort() function
41PHP Programming with MySQL, 2nd Edition
Combining Arrays
• To append one array to another, use the
addition (+) or the compound assignment
operator (+=)
• To merge two or more arrays use the
array_merge() function
• The syntax for the array_merge() function is:
new_array = array_merge($array1, $array2,
$array3, ...);
42PHP Programming with MySQL, 2nd Edition
Combining Arrays (continued)
$Provinces = array("Newfoundland and Labrador",
"Prince Edward Island", "Nova Scotia", "New
Brunswick", "Quebec", "Ontario", "Manitoba",
"Saskatchewan", "Alberta", "British
Columbia");
$Territories = array("Nunavut", "Northwest
Territories", "Yukon Territory");
$Canada = $Provinces + $Territories;
echo "<pre>n";
print_r($Canada);
echo "</pre>n";
43PHP Programming with MySQL, 2nd Edition
Combining Arrays (continued)
Figure 6-12 Output of two indexed arrays combined with the
addition operator
44PHP Programming with MySQL, 2nd Edition
Comparing Arrays
• The array_diff() function returns an array of
elements that exist in one array but not in any
other arrays to which it is compared
• The syntax for the array_diff() function is:
new_array = array_diff($array1, $array2,
$array3, ...);
• The array_intersect() function returns an
array of elements that exist in all of the arrays
that are compared
45PHP Programming with MySQL, 2nd Edition
Comparing Arrays (continued)
• The syntax for the array_intersect()
function is:
new_array = array_intersect($array1,
$array2, $array3, ...);
46PHP Programming with MySQL, 2nd Edition
Comparing Arrays (continued)
$ProvincialCapitals = array("Newfoundland and Labrador"=>"St.
John's", "Prince Edward Island"=>"Charlottetown", "Nova
Scotia"=>"Halifax", "New Brunswick"=>"Fredericton",
"Quebec"=>"Quebec City", "Ontario"=>"Toronto",
"Manitoba"=>"Winnipeg", "Saskatchewan"=>"Regina",
"Alberta"=>"Edmonton", "British Columbia"=>"Victoria");
$TerritorialCapitals = array("Nunavut"=>"Iqaluit", "Northwest
Territories"=>"Yellowknife", "Yukon Territory"=>"Whitehorse");
$CanadianCapitals = $ProvincialCapitals + $TerritorialCapitals;
echo "<pre>n";
print_r($CanadianCapitals);
echo "</pre>n";
47PHP Programming with MySQL, 2nd Edition
Comparing Arrays (continued)
Figure 6-20 Output of an array created with the
array_intersect() function
48PHP Programming with MySQL, 2nd Edition
Comparing Arrays (continued)
$Provinces = array("Newfoundland and Labrador",
"Prince Edward Island", "Nova Scotia", "New
Brunswick", "Quebec", "Ontario", "Manitoba",
"Saskatchewan", "Alberta", "British
Columbia");
$Territories = array("Nunavut", "Northwest
Territories", "Yukon Territory");
$Canada = array_merge($Provinces, $Territories);
49PHP Programming with MySQL, 2nd Edition
Creating Two-Dimensional
Indexed Arrays
• A multidimensional array consists of multiple
indexes or keys
• A two-dimensional array has two sets of
indexes or keys
50PHP Programming with MySQL, 2nd Edition
Creating Two-Dimensional
Indexed Arrays (continued)
$Gallons = array(
128, // ounces
16, // cups
8, // pints
4 // quarts
);
51PHP Programming with MySQL, 2nd Edition
Creating Two-Dimensional
Indexed Arrays (continued)
$Ounces = array(1, 0.125, 0.0625, 0.03125,
0.0078125);
$Cups = array(8, 1, 0.5, 0.25, 0.0625);
$Pints = array(16, 2, 1, 0.5, 0.125);
$Quarts = array(32, 4, 2, 1, 0.25);
$Gallons = array(128, 16, 8, 4, 1);
52PHP Programming with MySQL, 2nd Edition
Creating Two-Dimensional
Indexed Arrays (continued)
$VolumeConversions = array($Ounces, $Cups,
$Pints, $Quarts, $Gallons);
53PHP Programming with MySQL, 2nd Edition
Creating Two-Dimensional
Associative Arrays
$Ounces = array("ounces" => 1, "cups" => 0.125, "pints" =>
0.0625, "quarts" => 0.03125, "gallons" => 0.0078125);
$Cups = array("ounces" => 8, "cups" => 1, "pints" =>0.5,
"quarts" => 0.25, "gallons" => 0.0625);
$Pints = array("ounces" => 16, "cups" => 2, "pints" =>1,
"quarts" => 0.5, "gallons" => 0.125);
$Quarts = array("ounces" => 32, "cups" => 4, "pints" =>2,
"quarts" => 1, "gallons" => 0.25);
$Gallons = array("ounces" => 128, "cups" => 16, "pints"
=>8, "quarts" => 4, "gallons" => 1);
54PHP Programming with MySQL, 2nd Edition
Creating Two-Dimensional
Associative Arrays (continued)
Figure 6-21 Elements and keys in the
$VolumeConversions[ ] array
55PHP Programming with MySQL, 2nd Edition
Creating Multidimensional Arrays
with a Single Statement
$VolumeConversions = array(
array(1, 0.125, 0.0625, 0.03125, 0.0078125), // Ounces
array(8, 1, 0.5, 0.25, 0.0625), // Cups
array(16, 2, 1, 0.5, 0.125), // Pints
array(32, 4, 2, 1, 0.25), // Quarts
array(128, 16, 8, 4, 1) // Gallons
);
56PHP Programming with MySQL, 2nd Edition
Working with Additional
Dimensions
Using Arrays in Web Forms
• Store form data in an array by appending an
opening and closing ([]) to the value of the
name attribute
• Data from any element with the same value for
the name attribute will be appended to an array
with that name
57PHP Programming with MySQL, 2nd Edition
Using Arrays in Web Forms
(continued)
<form method='post' action='ProcessForm.php'>
<p>Enter the first answer:
<input type='text' name='answers[]' /></p>
<p>Enter the second answer:
<input type='text' name='answers[]' /></p>
<p>Enter the third answer:
<input type='text' name='answers[]' /></p>
<input type='submit' name='submit'
value='submit' />
</form>
58PHP Programming with MySQL, 2nd Edition
Using Arrays in Web Forms
(continued)
if (is_array($_POST['answers')) {
$Index = 0;
foreach ($_POST['answers'] as $Answer) {
++$Index;
echo "The answer for question $Index
is '$Answer'<br />n";
}
}
59PHP Programming with MySQL, 2nd Edition
Using Arrays in Web Forms
(continued)
60PHP Programming with MySQL, 2nd Edition
Figure 6-22 Output of an array posted from a Web form
Using Multidimensional Array
Notation
• Multidimensional array notation can also be
used to process posted form information
if (is_array($_POST['answers')) {
$count = count($_POST['answers']);
for ($i=0; $i<$count; ++$i) {
echo "The answer for question " .
($i+1) . " is '{$_POST['answers'][$i]}'<br
/>n";
}
}
61PHP Programming with MySQL, 2nd Edition
Creating an Associative Forms
Array
<form method='post' action='ProcessForm.php'>
<p>Enter the first answer:
<input type='text' name='answers[Question 1]' /></p>
<p>Enter the second answer:
<input type='text' name='answers[Question 2]' /></p>
<p>Enter the third answer:
<input type='text' name='answers[Question 3]' /></p>
<input type='submit' name='submit' value='submit' />
</form>
62PHP Programming with MySQL, 2nd Edition
63PHP Programming with MySQL, 2nd Edition
Summary
• The array_shift() function removes the first
element from the beginning of an array
• The array_unshift() function adds one or
more elements to the beginning of an array
• The array_pop() function removes the last
element from the end of an array
• The array_push() function adds one or more
elements to the end of an array
• The array_splice() function adds or
removes array elements
64PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The unset() function removes array elements
and other variables
• The array_values() function renumbers an
indexed array’s elements
• The array_unique() function removes
duplicate elements from an array
• The in_array() function returns a Boolean
value of TRUE if a given value exists in an array
• The array_search() function determines
whether a given value exists in an array
65PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The array_key_exists() function
determines whether a given index or key exists
• The array_slice() function returns a portion
of an array and assigns it to another array
• The array_merge() function merges two or
more arrays
• The array_diff() function returns an array of
elements that exist in one array but not in any
other arrays to which it is compared
66PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The array_intersect() function returns an
array of elements that exist in all of the arrays
that are compared
• A multidimensional array consists of multiple
sets of indexes or keys
• A two-dimensional array has two sets of
indexes or keys
• When array notation is used in the name of a
Web form input, the value gets stored in a
nested array within the $_POST or $_GET array
67PHP Programming with MySQL, 2nd Edition
Summary (continued)
• When using associative array notation in a Web
form, you omit the quotation marks around the
key name

More Related Content

What's hot

Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
Harit Kothari
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - Thaipt
Framgia Vietnam
 
Java class 8
Java class 8Java class 8
Java class 8
Edureka!
 

What's hot (20)

MySQL Replication Evolution -- Confoo Montreal 2017
MySQL Replication Evolution -- Confoo Montreal 2017MySQL Replication Evolution -- Confoo Montreal 2017
MySQL Replication Evolution -- Confoo Montreal 2017
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Development
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
 
lab56_db
lab56_dblab56_db
lab56_db
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
 
Mysql
MysqlMysql
Mysql
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
MySQL
MySQLMySQL
MySQL
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - Thaipt
 
Java class 8
Java class 8Java class 8
Java class 8
 
Optimizing queries MySQL
Optimizing queries MySQLOptimizing queries MySQL
Optimizing queries MySQL
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
Oracle Database 12c - Data Redaction
Oracle Database 12c - Data RedactionOracle Database 12c - Data Redaction
Oracle Database 12c - Data Redaction
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
Oracle Database 12.1.0.2 New Features
Oracle Database 12.1.0.2 New FeaturesOracle Database 12.1.0.2 New Features
Oracle Database 12.1.0.2 New Features
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 

Similar to 9780538745840 ppt ch06

Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvvLecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
ZahouAmel1
 
Lecture no 9.ppt operating system semester four
Lecture  no 9.ppt operating system semester fourLecture  no 9.ppt operating system semester four
Lecture no 9.ppt operating system semester four
VaibhavBhagwat18
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
PHP record- with all programs and output
PHP record- with all programs and outputPHP record- with all programs and output
PHP record- with all programs and output
KavithaK23
 

Similar to 9780538745840 ppt ch06 (20)

Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
javascript-Array.ppsx
javascript-Array.ppsxjavascript-Array.ppsx
javascript-Array.ppsx
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
Using arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing informationUsing arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing information
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvvLecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
 
Lecture no 9.ppt operating system semester four
Lecture  no 9.ppt operating system semester fourLecture  no 9.ppt operating system semester four
Lecture no 9.ppt operating system semester four
 
Php array
Php arrayPhp array
Php array
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Chapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statementsChapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statements
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppttutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl course
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
PHP record- with all programs and output
PHP record- with all programs and outputPHP record- with all programs and output
PHP record- with all programs and output
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 

More from Terry Yoast

More from Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 

Recently uploaded

Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 

Recently uploaded (20)

MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 

9780538745840 ppt ch06

  • 1. Chapter 6 Manipulating Arrays PHP Programming with MySQL 2nd Edition
  • 2. 2PHP Programming with MySQL, 2nd Edition Objectives In this chapter, you will: • Manipulate array elements • Declare and initialize associative arrays • Iterate through an array • Find and extract elements and values • Sort, combine, and compare arrays • Understand multidimensional arrays • Use arrays in Web forms
  • 3. 3PHP Programming with MySQL, 2nd Edition Manipulating Elements if (isset($_POST['submit'])) { $Subject = stripslashes($_POST['subject']); $Name = stripslashes($_POST['name']); $Message = stripslashes($_POST['message']); // Replace any '~' characters with '-' characters $Subject = str_replace("~", "-", $Subject); $Name = str_replace("~", "-", $Name); $Message = str_replace("~", "-", $Message); $MessageRecord = "$Subject~$Name~$Messagen"; $MessageFile = fopen("MessageBoard/messages.txt", "ab"); if ($MessageFile === FALSE) echo "There was an error saving your message!n"; else { fwrite($MessageFile, $MessageRecord); fclose($MessageFile); echo "Your message has been saved.n"; } }
  • 4. 4PHP Programming with MySQL, 2nd Edition Manipulating Elements (continued) <h1>Post New Message</h1> <hr /> <form action="PostMessage.php" method="POST"> <strong>Subject:</strong> <input type="text" name="subject" /> <strong>Name:</strong> <input type="text" name="name" /><br /> <textarea name="message" rows="6" cols="80"></textarea><br /> <input type="submit" name="submit" value="Post Message" /> <input type="reset" name="reset" value="Reset Form" /> </form> <hr /> <a href="MessageBoard.php">View Messages</a>
  • 5. 5PHP Programming with MySQL, 2nd Edition Manipulating Elements (continued) Figure 6-1 Post New Message page of the Message Board
  • 6. Manipulating Elements (continued) <h1>Message Board</h1> <?php ?> <p> <a href="PostMessage.php">Post New Message</a> </p> if ((!file_exists("MessageBoard/messages.txt")) || (filesize("MessageBoard/messages.txt") == 0)) echo "<p>There are no messages posted.</p>n"; } else { $MessageArray = file("MessageBoard/messages.txt"); echo "<table style="background-color:lightgray" border="1" width="100%">n"; $count = count($MessageArray); 6PHP Programming with MySQL, 2nd Edition
  • 7. Manipulating Elements (continued) for ($i = 0; $i < $count; ++$i) { $CurrMsg = explode("~", $MessageArray[$i]); echo " <tr>n"; echo " <td width="5%" align="center"><strong>" . ($i + 1) . "</strong></td>n"; echo " <td width="95%"><strong>Subject:</strong> " . htmlentities($CurrMsg[0]) . "<br />"; echo "<strong>Name:</strong> " . htmlentities($CurrMsg[1]) . "<br />"; echo "<u><strong>Message</strong></u><br />" . htmlentities($CurrMsg[2]) . "</td>n"; echo " </tr>n"; } echo "</table>n"; 7PHP Programming with MySQL, 2nd Edition
  • 8. 8PHP Programming with MySQL, 2nd Edition Manipulating Elements (continued) Figure 6-2 Message Board page of the Message Board
  • 9. 9PHP Programming with MySQL, 2nd Edition Adding and Removing Elements from the Beginning of an Array • The array_shift() function removes the first element from the beginning of an array – Pass the name of the array whose first element you want to remove • The array_unshift() function adds one or more elements to the beginning of an array – Pass the name of an array followed by comma- separated values for each element you want to add
  • 10. 10PHP Programming with MySQL, 2nd Edition Adding and Removing Elements from the Beginning of an Array (continued) $TopSellers = array( "Chevrolet Impala", "Chevrolet Malibu", "Chevrolet Silverado", "Ford F-Series", "Toyota Camry", "Toyota Corolla", "Nissan Altima", "Honda Accord", "Honda Civic", "Dodge Ram"); array_shift($TopSellers); array_unshift($TopSellers, "Honda CR-V"); echo "<pre>n"; print_r($TopSellers); echo "</pre>n";
  • 11. 11PHP Programming with MySQL, 2nd Edition Adding and Removing Elements from the Beginning of an Array (continued) Figure 6-3 Output of an array modified with the array_shift() and array_unshift() functions
  • 12. 12PHP Programming with MySQL, 2nd Edition Adding and Removing Elements from the End of an Array • The array_pop() function removes the last element from the end of an array – Pass the name of the array whose last element you want to remove • The array_push() function adds one or more elements to the end of an array – Pass the name of an array followed by comma-separated values for each element you want to add
  • 13. 13PHP Programming with MySQL, 2nd Edition Adding and Removing Elements from the End of an Array (continued) $HospitalDepts = array( "Anesthesia", "Molecular Biology", "Neurology", "Pediatrics"); array_pop($HospitalDepts); // Removes "Pediatrics" array_push($HospitalDepts, "Psychiatry", "Pulmonary Diseases");
  • 14. 14PHP Programming with MySQL, 2nd Edition Adding and Removing Elements Within an Array • The array_splice() function adds or removes array elements • The array_splice() function renumbers the indexes in the array • The syntax for the array_splice() function is: array_splice(array_name, start, characters_to_delete, values_to_insert);
  • 15. 15PHP Programming with MySQL, 2nd Edition Adding and Removing Elements Within an Array (continued) • To add an element within an array, include a value of 0 as the third argument of the array_splice() function $HospitalDepts = array( "Anesthesia", // first element (0) "Molecular Biology", // second element (1) "Neurology", // third element (2) "Pediatrics"); // fourth element (3) array_splice($HospitalDepts, 3, 0, "Ophthalmology");
  • 16. 16PHP Programming with MySQL, 2nd Edition Adding and Removing Elements Within an Array (continued) • To add more than one element within an array, pass the array() construct as the fourth argument of the array_splice() function • Separate the new element values by commas $HospitalDepts = array( "Anesthesia", // first element (0) "Molecular Biology", // second element (1) "Neurology", // third element (2) "Pediatrics"); // fourth element (3) array_splice($HospitalDepts, 3, 0, array("Opthalmology", "Otolaryngology"));
  • 17. 17PHP Programming with MySQL, 2nd Edition Adding and Removing Elements Within an Array (continued) • Delete array elements by omitting the fourth argument from the array_splice() function $HospitalDepts = array( "Anesthesia", // first element (0) "Molecular Biology", // second element (1) "Neurology", // third element (2) "Pediatrics"); // fourth element (3) array_splice($HospitalDepts, 1, 2);
  • 18. 18PHP Programming with MySQL, 2nd Edition Adding and Removing Elements Within an Array (continued) • The unset() function removes array elements and other variables • Pass to the unset() function the array name and index number of the element you want to remove • To remove multiple elements, separate each index name and element number with commas unset($HospitalDepts[1], $HospitalDepts[2]);
  • 19. 19PHP Programming with MySQL, 2nd Edition Removing Duplicate Elements • The array_unique() function removes duplicate elements from an array • Pass to the array_unique() function the name of the array from which you want to remove duplicate elements • The array_values() and array_unique() functions do not operate directly on an array • The array_unique() function does renumber the indexes after removing duplicate values in an array
  • 20. 20PHP Programming with MySQL, 2nd Edition Removing Duplicate Elements (continued) $TopSellers = array( "Ford F-Series", "Chevrolet Silverado", "Toyota Camry", "Honda Accord", "Toyota Corolla", "Ford F-Series", "Honda Civic", "Honda CR-V", "Honda Accord", "Nissan Altima", "Toyota Camry", "Chevrolet Impala", "Dodge Ram", "Honda CR-V"); echo "<p>The 2008 top selling vehicles are:</p><p>"; $TopSellers = array_unique($TopSellers); $TopSellers = array_values($TopSellers); for ($i=0; $i<count($ TopSellers); ++$i) { echo "{$TopSellers[$i]}<br />"; } echo "</p>";
  • 21. 21PHP Programming with MySQL, 2nd Edition Removing Duplicate Elements (continued) Figure 6-4 Output of an array after removing duplicate values with the array_unique() function
  • 22. 22PHP Programming with MySQL, 2nd Edition Declaring and Initializing Associative Arrays • With associative arrays, you specify an element’s key by using the array operator (=>) – The syntax for declaring and initializing an associative array is: $array_name = array(key=>value, ...); Figure 6-5 Output of array with associative and indexed elements
  • 23. 23PHP Programming with MySQL, 2nd Edition Declaring and Initializing Associative Arrays (continued) $Territories[100] = "Nunavut"; $Territories[] = "Northwest Territories"; $Territories[] = "Yukon Territory"; echo "<pre>n"; print_r($Territories); echo "</pre>n"; echo '<p>The $Territories array consists of ', count($Territories), " elements.</p>n"; Figure 6-6 Output of an array with a starting index of 100
  • 24. 24PHP Programming with MySQL, 2nd Edition Iterating Through an Array • The internal array pointer refers to the currently selected element in an array
  • 25. 25PHP Programming with MySQL, 2nd Edition Iterating Through an Array (continued) Figure 6-8 Output of an array without advancing the internal array pointer
  • 26. 26PHP Programming with MySQL, 2nd Edition Finding and Extracting Elements and Values • One of the most basic methods for finding a value in an array is to use a looping statement to iterate through the array until you find the value • Rather than write custom code to find a value, use the in_array() and array_search() functions to determine whether a value exists in an array
  • 27. 27PHP Programming with MySQL, 2nd Edition Determining if a Value Exists • The in_array() function returns a Boolean value of true if a given value exists in an array • The array_search() function determines whether a given value exists in an array and: – Returns the index or key of the first matching element if the value exists, or – Returns FALSE if the value does not exist if (in_array("Neurology", $HospitalDepts)) echo "<p>The hospital has a Neurology department.</p>";
  • 28. 28PHP Programming with MySQL, 2nd Edition Determining if a Key Exists • The array_key_exists() function determines whether a given index or key exists • You pass two arguments to the array_key_exists() function: – The first argument represents the key to search for – The second argument represents the name of the array in which to search
  • 29. 29PHP Programming with MySQL, 2nd Edition Determining if a Key Exists (continued) $ScreenNames["Dancer"] = "Daryl"; $ScreenNames["Fat Man"] = "Dennis"; $ScreenNames["Assassin"] = "Jennifer"; if (array_key_exists("Fat Man", $ScreenNames)) echo "<p>{$ScreenNames['Fat Man']} is already 'Fat Man'.</p>n"; else { $ScreenNames["Fat Man"] = "Don"; echo "<p>{$ScreenNames['Fat Man']} is now 'Fat Man'.</p>"; }
  • 30. 30PHP Programming with MySQL, 2nd Edition Returning a Portion of an Array • The array_slice() function returns a portion of an array and assigns it to another array • The syntax for the array_slice() function is: array_slice(array_name, start, characters_to_return);
  • 31. 31PHP Programming with MySQL, 2nd Edition Returning a Portion of an Array (continued) // This array is ordered by sales, high to low. $TopSellers = array("Ford F-Series", "Chevrolet Silverado", "Toyota Camry", "Honda Accord", "Toyota Corolla", "Honda Civic", "Nissan Altima", "Chevrolet Impala", "Dodge Ram", "Honda CR-V"); $FiveTopSellers = array_slice($TopSellers, 0, 5); echo "<p>The five best-selling vehicles for 2008 are:</p>n"; for ($i=0; $i<count($FiveTopSellers); ++$i) { echo "{$FiveTopSellers[$i]}<br />n"; }
  • 32. 32PHP Programming with MySQL, 2nd Edition Returning a Portion of an Array (continued) Figure 6-11 Output of an array returned with the array_slice() function
  • 33. 33PHP Programming with MySQL, 2nd Edition Sorting Arrays • The most commonly used array sorting functions are: – sort() and rsort() for indexed arrays – ksort() and krsort() for associative arrays
  • 34. 34PHP Programming with MySQL, 2nd Edition Sorting Arrays (continued)
  • 35. 35PHP Programming with MySQL, 2nd Edition Sorting Arrays (continued)
  • 36. 36PHP Programming with MySQL, 2nd Edition Sorting Arrays (continued) • If the sort() and rsort() functions are used on an associative array, the keys are replaced with indexes
  • 37. 37PHP Programming with MySQL, 2nd Edition Sorting Arrays (continued) Figure 6-12 Output of an array after applying the sort() and rsort() functions
  • 38. 38PHP Programming with MySQL, 2nd Edition Sorting Arrays (continued) Figure 6-13 Output of an associative array after sorting with the sort() function
  • 39. 39PHP Programming with MySQL, 2nd Edition Sorting Arrays (continued) Figure 6-14 Output of an associative array after sorting with the asort() function
  • 40. 40PHP Programming with MySQL, 2nd Edition Sorting Arrays (continued) Figure 6-15 Output of an associative array after sorting with the ksort() function
  • 41. 41PHP Programming with MySQL, 2nd Edition Combining Arrays • To append one array to another, use the addition (+) or the compound assignment operator (+=) • To merge two or more arrays use the array_merge() function • The syntax for the array_merge() function is: new_array = array_merge($array1, $array2, $array3, ...);
  • 42. 42PHP Programming with MySQL, 2nd Edition Combining Arrays (continued) $Provinces = array("Newfoundland and Labrador", "Prince Edward Island", "Nova Scotia", "New Brunswick", "Quebec", "Ontario", "Manitoba", "Saskatchewan", "Alberta", "British Columbia"); $Territories = array("Nunavut", "Northwest Territories", "Yukon Territory"); $Canada = $Provinces + $Territories; echo "<pre>n"; print_r($Canada); echo "</pre>n";
  • 43. 43PHP Programming with MySQL, 2nd Edition Combining Arrays (continued) Figure 6-12 Output of two indexed arrays combined with the addition operator
  • 44. 44PHP Programming with MySQL, 2nd Edition Comparing Arrays • The array_diff() function returns an array of elements that exist in one array but not in any other arrays to which it is compared • The syntax for the array_diff() function is: new_array = array_diff($array1, $array2, $array3, ...); • The array_intersect() function returns an array of elements that exist in all of the arrays that are compared
  • 45. 45PHP Programming with MySQL, 2nd Edition Comparing Arrays (continued) • The syntax for the array_intersect() function is: new_array = array_intersect($array1, $array2, $array3, ...);
  • 46. 46PHP Programming with MySQL, 2nd Edition Comparing Arrays (continued) $ProvincialCapitals = array("Newfoundland and Labrador"=>"St. John's", "Prince Edward Island"=>"Charlottetown", "Nova Scotia"=>"Halifax", "New Brunswick"=>"Fredericton", "Quebec"=>"Quebec City", "Ontario"=>"Toronto", "Manitoba"=>"Winnipeg", "Saskatchewan"=>"Regina", "Alberta"=>"Edmonton", "British Columbia"=>"Victoria"); $TerritorialCapitals = array("Nunavut"=>"Iqaluit", "Northwest Territories"=>"Yellowknife", "Yukon Territory"=>"Whitehorse"); $CanadianCapitals = $ProvincialCapitals + $TerritorialCapitals; echo "<pre>n"; print_r($CanadianCapitals); echo "</pre>n";
  • 47. 47PHP Programming with MySQL, 2nd Edition Comparing Arrays (continued) Figure 6-20 Output of an array created with the array_intersect() function
  • 48. 48PHP Programming with MySQL, 2nd Edition Comparing Arrays (continued) $Provinces = array("Newfoundland and Labrador", "Prince Edward Island", "Nova Scotia", "New Brunswick", "Quebec", "Ontario", "Manitoba", "Saskatchewan", "Alberta", "British Columbia"); $Territories = array("Nunavut", "Northwest Territories", "Yukon Territory"); $Canada = array_merge($Provinces, $Territories);
  • 49. 49PHP Programming with MySQL, 2nd Edition Creating Two-Dimensional Indexed Arrays • A multidimensional array consists of multiple indexes or keys • A two-dimensional array has two sets of indexes or keys
  • 50. 50PHP Programming with MySQL, 2nd Edition Creating Two-Dimensional Indexed Arrays (continued) $Gallons = array( 128, // ounces 16, // cups 8, // pints 4 // quarts );
  • 51. 51PHP Programming with MySQL, 2nd Edition Creating Two-Dimensional Indexed Arrays (continued) $Ounces = array(1, 0.125, 0.0625, 0.03125, 0.0078125); $Cups = array(8, 1, 0.5, 0.25, 0.0625); $Pints = array(16, 2, 1, 0.5, 0.125); $Quarts = array(32, 4, 2, 1, 0.25); $Gallons = array(128, 16, 8, 4, 1);
  • 52. 52PHP Programming with MySQL, 2nd Edition Creating Two-Dimensional Indexed Arrays (continued) $VolumeConversions = array($Ounces, $Cups, $Pints, $Quarts, $Gallons);
  • 53. 53PHP Programming with MySQL, 2nd Edition Creating Two-Dimensional Associative Arrays $Ounces = array("ounces" => 1, "cups" => 0.125, "pints" => 0.0625, "quarts" => 0.03125, "gallons" => 0.0078125); $Cups = array("ounces" => 8, "cups" => 1, "pints" =>0.5, "quarts" => 0.25, "gallons" => 0.0625); $Pints = array("ounces" => 16, "cups" => 2, "pints" =>1, "quarts" => 0.5, "gallons" => 0.125); $Quarts = array("ounces" => 32, "cups" => 4, "pints" =>2, "quarts" => 1, "gallons" => 0.25); $Gallons = array("ounces" => 128, "cups" => 16, "pints" =>8, "quarts" => 4, "gallons" => 1);
  • 54. 54PHP Programming with MySQL, 2nd Edition Creating Two-Dimensional Associative Arrays (continued) Figure 6-21 Elements and keys in the $VolumeConversions[ ] array
  • 55. 55PHP Programming with MySQL, 2nd Edition Creating Multidimensional Arrays with a Single Statement $VolumeConversions = array( array(1, 0.125, 0.0625, 0.03125, 0.0078125), // Ounces array(8, 1, 0.5, 0.25, 0.0625), // Cups array(16, 2, 1, 0.5, 0.125), // Pints array(32, 4, 2, 1, 0.25), // Quarts array(128, 16, 8, 4, 1) // Gallons );
  • 56. 56PHP Programming with MySQL, 2nd Edition Working with Additional Dimensions
  • 57. Using Arrays in Web Forms • Store form data in an array by appending an opening and closing ([]) to the value of the name attribute • Data from any element with the same value for the name attribute will be appended to an array with that name 57PHP Programming with MySQL, 2nd Edition
  • 58. Using Arrays in Web Forms (continued) <form method='post' action='ProcessForm.php'> <p>Enter the first answer: <input type='text' name='answers[]' /></p> <p>Enter the second answer: <input type='text' name='answers[]' /></p> <p>Enter the third answer: <input type='text' name='answers[]' /></p> <input type='submit' name='submit' value='submit' /> </form> 58PHP Programming with MySQL, 2nd Edition
  • 59. Using Arrays in Web Forms (continued) if (is_array($_POST['answers')) { $Index = 0; foreach ($_POST['answers'] as $Answer) { ++$Index; echo "The answer for question $Index is '$Answer'<br />n"; } } 59PHP Programming with MySQL, 2nd Edition
  • 60. Using Arrays in Web Forms (continued) 60PHP Programming with MySQL, 2nd Edition Figure 6-22 Output of an array posted from a Web form
  • 61. Using Multidimensional Array Notation • Multidimensional array notation can also be used to process posted form information if (is_array($_POST['answers')) { $count = count($_POST['answers']); for ($i=0; $i<$count; ++$i) { echo "The answer for question " . ($i+1) . " is '{$_POST['answers'][$i]}'<br />n"; } } 61PHP Programming with MySQL, 2nd Edition
  • 62. Creating an Associative Forms Array <form method='post' action='ProcessForm.php'> <p>Enter the first answer: <input type='text' name='answers[Question 1]' /></p> <p>Enter the second answer: <input type='text' name='answers[Question 2]' /></p> <p>Enter the third answer: <input type='text' name='answers[Question 3]' /></p> <input type='submit' name='submit' value='submit' /> </form> 62PHP Programming with MySQL, 2nd Edition
  • 63. 63PHP Programming with MySQL, 2nd Edition Summary • The array_shift() function removes the first element from the beginning of an array • The array_unshift() function adds one or more elements to the beginning of an array • The array_pop() function removes the last element from the end of an array • The array_push() function adds one or more elements to the end of an array • The array_splice() function adds or removes array elements
  • 64. 64PHP Programming with MySQL, 2nd Edition Summary (continued) • The unset() function removes array elements and other variables • The array_values() function renumbers an indexed array’s elements • The array_unique() function removes duplicate elements from an array • The in_array() function returns a Boolean value of TRUE if a given value exists in an array • The array_search() function determines whether a given value exists in an array
  • 65. 65PHP Programming with MySQL, 2nd Edition Summary (continued) • The array_key_exists() function determines whether a given index or key exists • The array_slice() function returns a portion of an array and assigns it to another array • The array_merge() function merges two or more arrays • The array_diff() function returns an array of elements that exist in one array but not in any other arrays to which it is compared
  • 66. 66PHP Programming with MySQL, 2nd Edition Summary (continued) • The array_intersect() function returns an array of elements that exist in all of the arrays that are compared • A multidimensional array consists of multiple sets of indexes or keys • A two-dimensional array has two sets of indexes or keys • When array notation is used in the name of a Web form input, the value gets stored in a nested array within the $_POST or $_GET array
  • 67. 67PHP Programming with MySQL, 2nd Edition Summary (continued) • When using associative array notation in a Web form, you omit the quotation marks around the key name