SlideShare a Scribd company logo
1 of 42
Using Arrays with PHP for Forms
and Storing Information
2
Objectives
In this chapter, you will:
Manipulate array elements
Explore associative arrays
Find and extract elements and values
Understand multidimensional arrays
Use arrays in Web forms
3
Message Board Example
4PHP Programming with MySQL, 2nd Edition
Message Board Example
5
Manipulating Elements (continued)
Code examples at:
http://zombieguineapigs.com/php
6PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
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
7PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements from
the Beginning of an Array
$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";
8
Adding and Removing Elements
9PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
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
10PHP Programming with MySQL, 2nd Edition
Adding and Removing Elements
$HospitalDepts = array(
"Anesthesia",
"Molecular Biology",
"Neurology",
"Pediatrics");
array_pop($HospitalDepts); // Removes "Pediatrics"
array_push($HospitalDepts, "Psychiatry", "Pulmonary
Diseases");
11
Adding and Removing Elements
The array_splice() function adds or removes
array elements
The array_splice() function renumbers the
indexes in the array
Syntax:
array_splice(array_name, start,
characters_to_delete, values_to_insert);
12
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");
13
Adding and Removing Elements
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"));
14PHP 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);
15
Adding and Removing Elements
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]);
16
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 renumbers the
indexes after removing duplicate values
17
Removing Duplicate Elements
$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>";
18
Removing Duplicate Elements
Figure 6-4 Output of an array after removing duplicate values
with the array_unique() function
19
Declaring and Initializing
Associative Arrays
With associative arrays, specify an element’s key
by using the array operator (=>)
$array_name = array(key=>value, ...);
20
Associative Arrays
$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";
21
Iterating Through an Array
The internal array pointer refers to the currently
selected element in an array
22
Iterating Through an Associative Array
Figure 6-8 Output of an array without advancing the internal
array pointer – See page 325
Iterating Through an Associative Array
To fix the issue on slide 22, use this code:
foreach ($ProvincialCapitals as $Capital) {
echo “The capital of : .
key($ProvincialCapitals) .
“ is $Capital<br />n”;
next($ProvincialCapitals);
23
Iterating Through an Associative Array
24
25
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
26
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>";
27
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
28
Determining if a Key Exists
$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>";
}
29PHP 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);
30
Returning a Portion of an Array
// 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";
}
31
Returning a Portion of an Array
Figure 6-11 Output of an array returned with the
array_slice() function
32
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
33
Two-Dimensional Indexed Arrays
$Gallons = array(
128, // ounces
16, // cups
8, // pints
4 // quarts
);
34
Two-Dimensional Indexed Arrays
$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);
35
Two-Dimensional Indexed Arrays
$VolumeConversions = array($Ounces, $Cups,
$Pints, $Quarts, $Gallons);
36
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);
37
Two-Dimensional Associative Arrays
Figure 6-21 Elements and keys in the
$VolumeConversions[ ] array
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
38
Using Arrays in Web Forms
<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>
39
Using Arrays in Web Forms
if (is_array($_POST['answers')) {
$Index = 0;
foreach ($_POST['answers'] as $Answer) {
++$Index;
echo "The answer for question $Index
is '$Answer'<br />n";
}
}
40
Using Arrays in Web Forms
41
Figure 6-22 Output of an array posted from a Web form
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>
42

More Related Content

What's hot

Decision trees in Machine Learning
Decision trees in Machine Learning Decision trees in Machine Learning
Decision trees in Machine Learning Mohammad Junaid Khan
 
EULER AND FERMAT THEOREM
EULER AND FERMAT THEOREMEULER AND FERMAT THEOREM
EULER AND FERMAT THEOREMankita pandey
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
Density Based Clustering
Density Based ClusteringDensity Based Clustering
Density Based ClusteringSSA KPI
 
Presentation on the topic selection sort
Presentation on the topic selection sortPresentation on the topic selection sort
Presentation on the topic selection sortDistrict Administration
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
NAIVE BAYES CLASSIFIER
NAIVE BAYES CLASSIFIERNAIVE BAYES CLASSIFIER
NAIVE BAYES CLASSIFIERKnoldus Inc.
 
Python lab manual all the experiments are available
Python lab manual all the experiments are availablePython lab manual all the experiments are available
Python lab manual all the experiments are availableNitesh Dubey
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
Hashing and separate chain
Hashing and separate chainHashing and separate chain
Hashing and separate chainVijayapriyaPandi
 

What's hot (20)

Quick sort
Quick sortQuick sort
Quick sort
 
Decision trees in Machine Learning
Decision trees in Machine Learning Decision trees in Machine Learning
Decision trees in Machine Learning
 
EULER AND FERMAT THEOREM
EULER AND FERMAT THEOREMEULER AND FERMAT THEOREM
EULER AND FERMAT THEOREM
 
Linked list
Linked listLinked list
Linked list
 
Java program structure
Java program structure Java program structure
Java program structure
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Density Based Clustering
Density Based ClusteringDensity Based Clustering
Density Based Clustering
 
Link list
Link listLink list
Link list
 
Presentation on the topic selection sort
Presentation on the topic selection sortPresentation on the topic selection sort
Presentation on the topic selection sort
 
Dbscan algorithom
Dbscan algorithomDbscan algorithom
Dbscan algorithom
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
NAIVE BAYES CLASSIFIER
NAIVE BAYES CLASSIFIERNAIVE BAYES CLASSIFIER
NAIVE BAYES CLASSIFIER
 
Python lab manual all the experiments are available
Python lab manual all the experiments are availablePython lab manual all the experiments are available
Python lab manual all the experiments are available
 
Lists
ListsLists
Lists
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
Hashing and separate chain
Hashing and separate chainHashing and separate chain
Hashing and separate chain
 

Viewers also liked

03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lformsIIUM
 
PHP Forms PHP 05
PHP Forms PHP 05PHP Forms PHP 05
PHP Forms PHP 05Spy Seat
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Michael Girouard
 
Chapter 07 php forms handling
Chapter 07   php forms handlingChapter 07   php forms handling
Chapter 07 php forms handlingDhani Ahmad
 
Php creating forms
Php creating formsPhp creating forms
Php creating formsargusacademy
 
Forms and Databases in PHP
Forms and Databases in PHPForms and Databases in PHP
Forms and Databases in PHPMike Crabb
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web ServicesBruno Pedro
 
Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2Pablo Godel
 

Viewers also liked (10)

03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lforms
 
PHP Forms PHP 05
PHP Forms PHP 05PHP Forms PHP 05
PHP Forms PHP 05
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
Chapter 07 php forms handling
Chapter 07   php forms handlingChapter 07   php forms handling
Chapter 07 php forms handling
 
3 php forms
3 php forms3 php forms
3 php forms
 
Php forms
Php formsPhp forms
Php forms
 
Php creating forms
Php creating formsPhp creating forms
Php creating forms
 
Forms and Databases in PHP
Forms and Databases in PHPForms and Databases in PHP
Forms and Databases in PHP
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web Services
 
Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2
 

Similar to Using arrays with PHP for forms and storing information

9780538745840 ppt ch06
9780538745840 ppt ch069780538745840 ppt ch06
9780538745840 ppt ch06Terry Yoast
 
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.pptxvvvvvvvvvvvvvvZahouAmel1
 
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 ...Dhivyaa C.R
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl courseBITS
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web ProgrammingAmirul Azhar
 
Using Arrays with Sorting and Searching Algorithms1) This program .pdf
Using Arrays with Sorting and Searching Algorithms1) This program .pdfUsing Arrays with Sorting and Searching Algorithms1) This program .pdf
Using Arrays with Sorting and Searching Algorithms1) This program .pdff3apparelsonline
 
EAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelEAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelKhoa Truong Dinh
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.pptAqeelAbbas94
 
PHP Array Functions.pptx
PHP Array Functions.pptxPHP Array Functions.pptx
PHP Array Functions.pptxKirenKinu
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 

Similar to Using arrays with PHP for forms and storing information (20)

9780538745840 ppt ch06
9780538745840 ppt ch069780538745840 ppt ch06
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
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
Php array
Php arrayPhp array
Php array
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
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
 
Unit 2-Arrays.pptx
Unit 2-Arrays.pptxUnit 2-Arrays.pptx
Unit 2-Arrays.pptx
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl course
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Array String - Web Programming
Array String - Web ProgrammingArray String - Web Programming
Array String - Web Programming
 
Array
ArrayArray
Array
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
Using Arrays with Sorting and Searching Algorithms1) This program .pdf
Using Arrays with Sorting and Searching Algorithms1) This program .pdfUsing Arrays with Sorting and Searching Algorithms1) This program .pdf
Using Arrays with Sorting and Searching Algorithms1) This program .pdf
 
EAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV ModelEAV Sytem- Magento EAV Model
EAV Sytem- Magento EAV Model
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt
 
PHP Array Functions.pptx
PHP Array Functions.pptxPHP Array Functions.pptx
PHP Array Functions.pptx
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 

More from Nicole Ryan

Testing and Improving Performance
Testing and Improving PerformanceTesting and Improving Performance
Testing and Improving PerformanceNicole Ryan
 
Optimizing a website for search engines
Optimizing a website for search enginesOptimizing a website for search engines
Optimizing a website for search enginesNicole Ryan
 
Javascript programming using the document object model
Javascript programming using the document object modelJavascript programming using the document object model
Javascript programming using the document object modelNicole Ryan
 
Working with Video and Audio
Working with Video and AudioWorking with Video and Audio
Working with Video and AudioNicole Ryan
 
Working with Images
Working with ImagesWorking with Images
Working with ImagesNicole Ryan
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and SetsNicole Ryan
 
Creating Visual Effects and Animation
Creating Visual Effects and AnimationCreating Visual Effects and Animation
Creating Visual Effects and AnimationNicole Ryan
 
Creating and Processing Web Forms
Creating and Processing Web FormsCreating and Processing Web Forms
Creating and Processing Web FormsNicole Ryan
 
Organizing Content with Lists and Tables
Organizing Content with Lists and TablesOrganizing Content with Lists and Tables
Organizing Content with Lists and TablesNicole Ryan
 
Social media and your website
Social media and your websiteSocial media and your website
Social media and your websiteNicole Ryan
 
Working with Links
Working with LinksWorking with Links
Working with LinksNicole Ryan
 
Formatting text with CSS
Formatting text with CSSFormatting text with CSS
Formatting text with CSSNicole Ryan
 
Laying Out Elements with CSS
Laying Out Elements with CSSLaying Out Elements with CSS
Laying Out Elements with CSSNicole Ryan
 
Getting Started with CSS
Getting Started with CSSGetting Started with CSS
Getting Started with CSSNicole Ryan
 
Structure Web Content
Structure Web ContentStructure Web Content
Structure Web ContentNicole Ryan
 
Getting Started with your Website
Getting Started with your WebsiteGetting Started with your Website
Getting Started with your WebsiteNicole Ryan
 
Chapter 12 Lecture: GUI Programming, Multithreading, and Animation
Chapter 12 Lecture: GUI Programming, Multithreading, and AnimationChapter 12 Lecture: GUI Programming, Multithreading, and Animation
Chapter 12 Lecture: GUI Programming, Multithreading, and AnimationNicole Ryan
 
Chapter 11: Object Oriented Programming Part 2
Chapter 11: Object Oriented Programming Part 2Chapter 11: Object Oriented Programming Part 2
Chapter 11: Object Oriented Programming Part 2Nicole Ryan
 
Intro to Programming: Modularity
Intro to Programming: ModularityIntro to Programming: Modularity
Intro to Programming: ModularityNicole Ryan
 

More from Nicole Ryan (20)

Testing and Improving Performance
Testing and Improving PerformanceTesting and Improving Performance
Testing and Improving Performance
 
Optimizing a website for search engines
Optimizing a website for search enginesOptimizing a website for search engines
Optimizing a website for search engines
 
Inheritance
InheritanceInheritance
Inheritance
 
Javascript programming using the document object model
Javascript programming using the document object modelJavascript programming using the document object model
Javascript programming using the document object model
 
Working with Video and Audio
Working with Video and AudioWorking with Video and Audio
Working with Video and Audio
 
Working with Images
Working with ImagesWorking with Images
Working with Images
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Creating Visual Effects and Animation
Creating Visual Effects and AnimationCreating Visual Effects and Animation
Creating Visual Effects and Animation
 
Creating and Processing Web Forms
Creating and Processing Web FormsCreating and Processing Web Forms
Creating and Processing Web Forms
 
Organizing Content with Lists and Tables
Organizing Content with Lists and TablesOrganizing Content with Lists and Tables
Organizing Content with Lists and Tables
 
Social media and your website
Social media and your websiteSocial media and your website
Social media and your website
 
Working with Links
Working with LinksWorking with Links
Working with Links
 
Formatting text with CSS
Formatting text with CSSFormatting text with CSS
Formatting text with CSS
 
Laying Out Elements with CSS
Laying Out Elements with CSSLaying Out Elements with CSS
Laying Out Elements with CSS
 
Getting Started with CSS
Getting Started with CSSGetting Started with CSS
Getting Started with CSS
 
Structure Web Content
Structure Web ContentStructure Web Content
Structure Web Content
 
Getting Started with your Website
Getting Started with your WebsiteGetting Started with your Website
Getting Started with your Website
 
Chapter 12 Lecture: GUI Programming, Multithreading, and Animation
Chapter 12 Lecture: GUI Programming, Multithreading, and AnimationChapter 12 Lecture: GUI Programming, Multithreading, and Animation
Chapter 12 Lecture: GUI Programming, Multithreading, and Animation
 
Chapter 11: Object Oriented Programming Part 2
Chapter 11: Object Oriented Programming Part 2Chapter 11: Object Oriented Programming Part 2
Chapter 11: Object Oriented Programming Part 2
 
Intro to Programming: Modularity
Intro to Programming: ModularityIntro to Programming: Modularity
Intro to Programming: Modularity
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Recently uploaded (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

Using arrays with PHP for forms and storing information

  • 1. Using Arrays with PHP for Forms and Storing Information
  • 2. 2 Objectives In this chapter, you will: Manipulate array elements Explore associative arrays Find and extract elements and values Understand multidimensional arrays Use arrays in Web forms
  • 4. 4PHP Programming with MySQL, 2nd Edition Message Board Example
  • 5. 5 Manipulating Elements (continued) Code examples at: http://zombieguineapigs.com/php
  • 6. 6PHP Programming with MySQL, 2nd Edition Adding and Removing Elements 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
  • 7. 7PHP Programming with MySQL, 2nd Edition Adding and Removing Elements from the Beginning of an Array $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";
  • 9. 9PHP Programming with MySQL, 2nd Edition Adding and Removing Elements 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
  • 10. 10PHP Programming with MySQL, 2nd Edition Adding and Removing Elements $HospitalDepts = array( "Anesthesia", "Molecular Biology", "Neurology", "Pediatrics"); array_pop($HospitalDepts); // Removes "Pediatrics" array_push($HospitalDepts, "Psychiatry", "Pulmonary Diseases");
  • 11. 11 Adding and Removing Elements The array_splice() function adds or removes array elements The array_splice() function renumbers the indexes in the array Syntax: array_splice(array_name, start, characters_to_delete, values_to_insert);
  • 12. 12 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");
  • 13. 13 Adding and Removing Elements 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"));
  • 14. 14PHP 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);
  • 15. 15 Adding and Removing Elements 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]);
  • 16. 16 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 renumbers the indexes after removing duplicate values
  • 17. 17 Removing Duplicate Elements $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>";
  • 18. 18 Removing Duplicate Elements Figure 6-4 Output of an array after removing duplicate values with the array_unique() function
  • 19. 19 Declaring and Initializing Associative Arrays With associative arrays, specify an element’s key by using the array operator (=>) $array_name = array(key=>value, ...);
  • 20. 20 Associative Arrays $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";
  • 21. 21 Iterating Through an Array The internal array pointer refers to the currently selected element in an array
  • 22. 22 Iterating Through an Associative Array Figure 6-8 Output of an array without advancing the internal array pointer – See page 325
  • 23. Iterating Through an Associative Array To fix the issue on slide 22, use this code: foreach ($ProvincialCapitals as $Capital) { echo “The capital of : . key($ProvincialCapitals) . “ is $Capital<br />n”; next($ProvincialCapitals); 23
  • 24. Iterating Through an Associative Array 24
  • 25. 25 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
  • 26. 26 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>";
  • 27. 27 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
  • 28. 28 Determining if a Key Exists $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>"; }
  • 29. 29PHP 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);
  • 30. 30 Returning a Portion of an Array // 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"; }
  • 31. 31 Returning a Portion of an Array Figure 6-11 Output of an array returned with the array_slice() function
  • 32. 32 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
  • 33. 33 Two-Dimensional Indexed Arrays $Gallons = array( 128, // ounces 16, // cups 8, // pints 4 // quarts );
  • 34. 34 Two-Dimensional Indexed Arrays $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);
  • 35. 35 Two-Dimensional Indexed Arrays $VolumeConversions = array($Ounces, $Cups, $Pints, $Quarts, $Gallons);
  • 36. 36 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);
  • 37. 37 Two-Dimensional Associative Arrays Figure 6-21 Elements and keys in the $VolumeConversions[ ] array
  • 38. 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 38
  • 39. Using Arrays in Web Forms <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> 39
  • 40. Using Arrays in Web Forms if (is_array($_POST['answers')) { $Index = 0; foreach ($_POST['answers'] as $Answer) { ++$Index; echo "The answer for question $Index is '$Answer'<br />n"; } } 40
  • 41. Using Arrays in Web Forms 41 Figure 6-22 Output of an array posted from a Web form
  • 42. 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> 42