PHP Programming with MySQL Slide 7-1 CHAPTER 7 Manipulating Arrays.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

Objectives Using functions to organize PHP code
PHP Using Arrays.
Canada. Provinces/Territories Nova Scotia Nova Scotia Newfoundland and Labrador Newfoundland and Labrador P.E.I P.E.I New Brunswick New Brunswick Ontario.
Functions & Arrays. Functions Functions offer the ability for programmers to group together program code that performs specific task or function into.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
C SCI 116.  What does $animals contain? 2 $animals = "ostrich"; $animals = "anteater"; $animals = "orangutan"; $animals = "cheetah"; $animals = "hyena";
Objectives Install and configure a Web server
PHP Introduction.
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
Objectives Connect to MySQL from PHP
Chapter 7 Manipulating Arrays PHP Programming with MySQL.
JavaScript, Fourth Edition
British Columbia Immigration Source: Citizenship and Immigration Canada Facts and Figures Immigration Overview Annual Number of Immigrants to British.

CANADA.
CSE 154 LECTURE 6: EMBEDDED PHP. PHP syntax template HTML content HTML content HTML content... PHP any contents of.
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizard’s Guide to PHP by David Lash.
VoiceXML Brandon Hannasch. Outline What is VoiceXML? Basic Tags Voice Recognition Audio Files Call Flow.
Authors : P K D. 1.Flag of Canada 2.Map of Canada 3.Introduction 4.Big Cities 5.Interesting Places.
Arrays By Shyam Gurram. What is an Array? An array can store one or more values in a single variable name. Each element in the array is assigned its own.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Microsoft Visual C++.NET Chapter 61 Memory Management.
1 Working with Data Types and Operators. 2 Using Variables and Constants The values stored in computer memory are called variables The values, or data,
CONFEDERATION of Canada.
Yukon Territory Northwest Territories British Columbia Alberta Pacific Ocean Beaufort Sea Arctic Ocean Saskatchewan Nunavut Manitoba OntarioQuebec Hudson.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Class 2Intro to Databases Goals of this class Include & Require in PHP Generating Random Numbers in PHP Arrays – Numerically Indexed and Associative Program.
Canada. New Brunswick Newfoundland Northwest Ter Nunavut Ontario Prince Edward Is. Quebec Saskatchewan Yukon Alberta British Columbia Manitoba Nova.
Canada in Maps Social Studies 10 Sutherland Secondary The Changing Face of Canada.
Bellwork: October 31 st Objective – Label major landforms, provinces, and territories of Canada 1.Here in the South, we grow up playing baseball, football,
Median Age. Lutheran Membership Lutheran population by mother tongue.
Canada By: Kiki Lochner, Meg Davies, and Chrissy dePenaloza Government.
Canada funnyv. What is Canada? Canada is a country in North America.
Canada Day By: Inderpreet Gill Inderpreet Gill1. Introduction  On Canada Day three colonies united into a single country called Canada within the British.
Canada. War  In the Canada there`s no war 10 provinces and 3 territories  Alberta  Manitoba  New-Brunswick  Newfoundland and Labrador  Nova Scotia.
By: Inderpreet Gill Inderpreet Gill 1. Introduction  Canada is a national holiday celebrating the anniversary on the July 1 st.  On Canada Day three.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
1 PHP Intro PHP Arrays After this lecture, you should be able to: Create and manipulate PHP Arrays: Create and manipulate PHP Arrays: Indexed Arrays Indexed.
PHP Constructs Advance Database Management Systems Lab no.3.
Slide 1 PHP Arrays and User Defined Functions ITWA133.
Instructions Step 1: Try to identify each of Canada’s province and territory. Click on the province to discover the answer Next.
Health of Canada. Trends for Obesity Trends in Diabetes.
By: Rachel and Melissa. Risks of Drunk Driving When you drive while under the influence you are putting yourself and other citizens at risk of a fatal.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
Canada List three facts you know about Canada.. Government 3 levels of government, Federal, Provincial and Municipal Federal Headed by Prime Minister.
Regions of Canada.
PHP Programming with MySQL Slide 3-1 CHAPTER 3 Working with Data Types and Operators.
ITM ITM 352 Array Processing. ITM Simple Array Processing  Arrays can be processed using iteration. Standard array-processing loop:  What.
Role of government policy in immigrant settlement and integration Ather H. Akbari Saint Mary’s University And Atlantic Research Group on Economics of Immigration,
NMD202 Web Scripting Week2. Web site
Creating PHP Pages Chapter 10 PHP Arrays. Arrays An array can store one or more values in a single variable name. An element of an associative accessed.
7 sec. 3 Subregions of Canada. Atlantic Provinces Prince Edward Island, New Brunswick, Nova Scotia, Newfoundland Very small population, logging and fishing.
Canada Oct.5, Missing Assignments - Sheet on continents Sheet on rivers and lakes Current events articles.
1 PHP Array PHP Arrays An indexed array is similar to one provided by a conventional programming language. An indexed array is similar to one provided.
CSE 154 LECTURE 15: EMBEDDED PHP. PHP syntax template HTML content HTML content HTML content... PHP any contents of.
2011 Occupational Therapist Provincial Reports 1.
JavaScript, Sixth Edition
Objectives In this chapter you will: Create PHP scripts
Illustrations of country and administry districts
Salut Goodbye: Last Five Years Saw increase in net loss of Quebecers owing to migration between the provinces Jack Jedwab Executive Vice President Association.
Chapter 6 Manipulating Arrays PHP Programming with MySQL 2nd Edition
Energy Fact Sleuths.
Objectives Install and configure a Web server
Canada.
A NEEDS REPORT ON ACCESSIBLE TECHNOLOGY  and  A DISCUSSION ON ACCESSIBLE ASSISTIVE TECHNOLOGY: SUMMARY REPORT Provided to the Accessible Technology Program.
Slide Deck 10: Federal Elections
Presentation transcript:

PHP Programming with MySQL Slide 7-1 CHAPTER 7 Manipulating Arrays

PHP Programming with MySQL Slide 7-2 Objectives Manipulate array elements Declare and initialize associative arrays Use iteration functions Find and extract elements and values Sort, combine, and compare arrays Work with multidimensional arrays

PHP Programming with MySQL Slide 7-3 Manipulating Elements $Topic = $_POST['topic']; $Name = $_POST['name']; $Message = $_POST['message']; $PostMessage = addslashes(“$Topic~$Name~$Message\n”); $MessageStore = fopen(“messages.txt”, “a”); fwrite($MessageStore, “$PostMessage”); fclose($MessageStore); echo “ Topic : $Topic ”; echo “ Name : $Name ”; echo “ Message : $Message ”;

PHP Programming with MySQL Slide 7-4 Manipulating Elements if (!file_exists(“messages.txt”) || filesize(“messages.txt”) == 0) echo “ There are no messages posted. ”; else { $MessageArray = file(“messages.txt”); for ($i=0; $i<count($MessageArray); ++$i) { $CurMessage = explode(“~”, $MessageArray[$i]); echo “ ”; echo “ ”. ($i + 1). “. ”; echo “ Topic : “. stripslashes($CurMessage[0]). “ ”; echo “ Name : “. stripslashes($CurMessage[1]). “ ”; echo “ Message : “. stripslashes($CurMessage[2]); echo “ ”; }

PHP Programming with MySQL Slide 7-5 Manipulating Elements (continued) Figure 7-1 Post New Message page of the Discussion Forum script

PHP Programming with MySQL Slide 7-6 Manipulating Elements Figure 7-2 Message Posted page of the Discussion Forum script

PHP Programming with MySQL Slide 7-7 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

PHP Programming with MySQL Slide 7-8 Adding and Removing Elements from the Beginning of an Array $TopGolfers = array( “Ernie Els”, “Phil Mickelson”, “Retief Goosen”, “Padraig Harrington”, “David Toms”, “Sergio Garcia”, “Adam Scott”, “Stewart Cink”); array_shift($TopGolfers); array_unshift($TopGolfers, “Tiger Woods”, “Vijay Singh”); print_r($TopGolfers);

PHP Programming with MySQL Slide 7-9 Adding and Removing Elements from the Beginning of an Array (continued) Figure 7-3 Output of an array modified with the array_shift() and array_unshift() functions

PHP Programming with MySQL Slide 7-10 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

PHP Programming with MySQL Slide 7-11 Adding and Removing Elements from the End of an Array $HospitalDepts = array( “Anesthesia”, “Molecular Biology”, “Neurology”, “Pediatrics”); array_pop($HospitalDepts); array_push($HospitalDepts, “Psychiatry”, “Pulmonary Diseases”);

PHP Programming with MySQL Slide 7-12 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);

PHP Programming with MySQL Slide 7-13 array_splice() Function To add an element within an array, include a value of 0 as the third argument $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”);

PHP Programming with MySQL Slide 7-14 array_splice() Function To add more than one element within an array, pass the array() construct as the fourth argument 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(“Ophthalmology”, “Otolaryngology”));

PHP Programming with MySQL Slide 7-15 array_splice() Function 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);

PHP Programming with MySQL Slide 7-16 unset() Function 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]);

PHP Programming with MySQL Slide 7-17 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

PHP Programming with MySQL Slide 7-18 array_unique() Function $TopGolfers = array( “Tiger Woods”, “Tiger Woods”, “Vijay Singh”, “Vijay Singh”, “Ernie Els”, “Phil Mickelson”, “Retief Goosen”, “Retief Goosen”, “Padraig Harrington”, “David Toms”, “Sergio Garcia”, “Adam Scott”, “Stewart Cink”); echo “ The world's top golfers are: ”; $TopGolfers = array_unique($TopGolfers); $TopGolfers = array_values($TopGolfers); for ($i=0; $i<count($TopGolfers); ++$i) { echo “{$TopGolfers[$i]} ”; } echo “ ”;

PHP Programming with MySQL Slide 7-19 array_unique() Function (continued) Figure 7-4 Output of an array after removing duplicate values with the array_unique() function

PHP Programming with MySQL Slide 7-20 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 7-5 Output of array with associative and indexed elements

PHP Programming with MySQL Slide 7-21 Declaring and Initializing Associative Arrays $Territories[100] = “Nunavut”; $Territories[] = “Northwest Territories”; $Territories[] = “Yukon Territory”; print_r($Territories); echo ' The $Territories array consists of ', count($Territories), “ elements. ”; Figure 7-6 Output of an array with a starting index of 100

PHP Programming with MySQL Slide 7-22 Iterating Through an Array The internal array pointer refers to the currently selected element in an array Table 7-1 Array pointer iteration functions

PHP Programming with MySQL Slide 7-23 Iterating Through an Array Figure 7-7 Output of an array without advancing the internal array pointer

PHP Programming with MySQL Slide 7-24 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 “ The hospital has a Neurology department. ”;

PHP Programming with MySQL Slide 7-25 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

PHP Programming with MySQL Slide 7-26 Determining if a Key Exists (continued) $GamePieces[“Dancer”] = “Daryl”; $GamePieces[“Fat Man”] = “Dennis”; $GamePieces[“Assassin”] = “Jennifer”; if (array_key_exists(“Fat Man”, $GamePieces)) echo “ {$GamePieces[“Fat Man”]} is already 'Fat Man'. ”; else { $GamePieces[“Fat Man”] = “Don”; echo “ {$GamePieces[“Fat Man”]} is now 'Fat Man'. ”; }

PHP Programming with MySQL Slide 7-27 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);

PHP Programming with MySQL Slide 7-28 Returning a Portion of an Array $TopGolfers = array(“Tiger Woods”, “Vijay Singh”, “Ernie Els”, “Phil Mickelson”, “Retief Goosen”, “Padraig Harrington”, “David Toms”, “Sergio Garcia”, “Adam Scott”, “Stewart Cink”); $TopFiveGolfers = array_slice($TopGolfers, 0, 5); echo “ The top five golfers in the world are: ”; for ($i=0; $i<count($TopFiveGolfers); ++$i) { echo “{$TopFiveGolfers[$i]} ”; } echo “ ”;

PHP Programming with MySQL Slide 7-29 Returning a Portion of an Array (continued) Figure 7-8 Output of an array returned with the array_slice() function

PHP Programming with MySQL Slide 7-30 Sorting Arrays The most commonly used array sorting functions are:  sort() and rsort() for indexed arrays  ksort() and krsort() for associative arrays

PHP Programming with MySQL Slide 7-31 Sorting Arrays Table 7-2 Array sorting functions

PHP Programming with MySQL Slide 7-32 Sorting Arrays Table 7-2 Array sorting functions (continued)

PHP Programming with MySQL Slide 7-33 Sorting Arrays Table 7-2 Array sorting functions (continued) If the sort() and rsort() functions are used on an associative array, the keys are replaced with indexes

PHP Programming with MySQL Slide 7-34 Sorting Arrays Figure 7-9 Output of an array after applying the sort() and rsort() functions

PHP Programming with MySQL Slide 7-35 Sorting Arrays Figure 7-10 Output of an associative array after executing the sort() function Figure 7-11 Output of an associative array after executing the ksort() function

PHP Programming with MySQL Slide 7-36 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,...);

PHP Programming with MySQL Slide 7-37 Combining Arrays $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; print_r($Canada); Figure 7-12 Output of two combined indexed arrays

PHP Programming with MySQL Slide 7-38 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

PHP Programming with MySQL Slide 7-39 Comparing Arrays The syntax for the array_intersect() function is: new_array = array_intersect($array1, $array2, $array3,...);

PHP Programming with MySQL Slide 7-40 Comparing Arrays Figure 7-13 Output of an array created with the array_intersect() function

PHP Programming with MySQL Slide 7-41 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

PHP Programming with MySQL Slide 7-42 Creating Two-Dimensional Indexed Arrays $USDollars = array( , // Yen , // Euro , // UK Pound , // Canadian Dollar // Swiss Francs ); Table 7-3 Currency conversion table

PHP Programming with MySQL Slide 7-43 Creating Two-Dimensional Indexed Arrays $USDollars = array(1, , , , , ); $Yen = array( , 1, , , , ); $Euro = array(1.3377, , 1, , , ); $UKPound = array(1.9239, , , 1, , ); $CanadianDollar = array(0.8324, , , , 1, ); $SwissFranc = array(0.8641, , , , , 1);

PHP Programming with MySQL Slide 7-44 Creating Two-Dimensional Indexed Arrays $ExchangeRates = array($USDollars, $Yen, $Euro, $UKPound, $CanadianDollar, $SwissFranc); Table 7-4 Elements and indexes in the $ExchangeRates[ ] array

PHP Programming with MySQL Slide 7-45 Creating Two-Dimensional Associative Arrays Figure 7-14 Elements and keys in the $ExchangeRates[ ] array

PHP Programming with MySQL Slide 7-46 Creating Multidimensional Arrays with a Single Statement $ExchangeRates = array( array(1, , , , , ), // U.S. $ array( , 1, , , , ), // Yen array(1.3377, , 1, , , ), // Euro array(1.9239, , , 1, , ), // U.K. Pound array(0.8324, , , , 1, ), // Canadian $ array(0.8641, , , , , 1) // Swiss Franc );

PHP Programming with MySQL Slide 7-47 Working with Additional Dimensions Table 7-5 The Alaska table of a three-dimensional array

PHP Programming with MySQL Slide 7-48 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

PHP Programming with MySQL Slide 7-49 Summary 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

PHP Programming with MySQL Slide 7-50 Summary 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_diff() function returns an array of elements that exist in one array but not in any other arrays to which it is compared The array_intersect() function returns an array of elements that exist in all of the arrays that are compared