C SCI 116.  What does $animals contain? 2 $animals = "ostrich"; $animals = "anteater"; $animals = "orangutan"; $animals = "cheetah"; $animals = "hyena";

Slides:



Advertisements
Similar presentations
» PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.
Advertisements

LIS651 lecture 3 functions and arrays Thomas Krichel
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Arrays.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, © Copyright 2010 All Rights Reserved. 1.
PHP Programming with MySQL Slide 7-1 CHAPTER 7 Manipulating Arrays.
Objectives Using functions to organize PHP code
PHP Using Arrays.
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.
ITC 240: Web Application Programming
PHP Introduction.
PHP Functions Composite Types. Functions  Declaration  function functionName(paramList) {  /* code goes here */ }  paramList is comma-separated list.
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
Chapter 7 Manipulating Arrays PHP Programming with MySQL.
JavaScript, Fourth Edition
Manipulating Strings. Name of Book2 Objectives Manipulate strings Parse strings Compare strings Handle form submissions.
CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals.
1 CS428 Web Engineering Lecture 19 Data Types (PHP - II)
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11 Introduction to PHP.
PHP – Get & Post; Functions; and Arrays IS6116 – 07 th February 2011.
DAY 4. Review: Strings Strings can be concatenated (joined together) using the. (period) operator: $fullName = “Thomas ”. “Bombach”; This works when outputting.
Chapter 3 Array. Indexed Versus Associative Arrays There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers,
Strings and Arrays. String Is a sequence of characters. Example: “hello”, “how are you?”, “123”,and are all valid string values.
Decisions, Loops, and Arrays Achmad Arwan, S.Kom.
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.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
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.
Lecture 5 – Function and Array SFDV3011 – Advanced Web Development 1.
Session 7 JavaScript/Jscript: Arrays Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
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,
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
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.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
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.
Array & Foreach อาร์เรย์และคำสั่งวนลูป. Content 1. Definition and Usage 2. Syntax 3. print_r() Statement 4. For and Foreach 5. Array Functions.
Class 2Intro to Databases Goals of this class Include & Require in PHP Generating Random Numbers in PHP Arrays – Numerically Indexed and Associative Program.
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.
CS 174: Web Programming September 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
PHP: A RRAYS, S TRINGS, AND F ILES CSCI 297 Scripting Languages - Day Three.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Kirkwood Center for Continuing Education Introduction to PHP and MySQL By Fred McClurg, © Copyright 2015, Fred McClurg, All Rights.
Slide 1 PHP Arrays and User Defined Functions ITWA133.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Project 1: Using Arrays and Manipulating Strings Essentials for Design JavaScript Level Two Michael Brooks.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
CHAPTER 7 Introduction to PHP5 Part II อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
PHP Programming with MySQL Slide 3-1 CHAPTER 3 Working with Data Types and Operators.
NMD202 Web Scripting Week2. Web site
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming javascript arrays.
CSC 4630 Meeting 17 March 21, Exam/Quiz Schedule Due to ice, travel, research and other commitments that we all have: –Quiz 2, scheduled for Monday.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
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.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
CGS 3066: Web Programming and Design Spring 2016 PHP.
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.
PHP Programming with MySQL Slide 5-1 CHAPTER 5 Manipulating Strings.
PHP using MySQL Database for Web Development (part II)
Arrays: Checkboxes and Textareas
Chapter 6 Manipulating Arrays PHP Programming with MySQL 2nd Edition
PHP an introduction.
Presentation transcript:

C SCI 116

 What does $animals contain? 2 $animals = "ostrich"; $animals = "anteater"; $animals = "orangutan"; $animals = "cheetah"; $animals = "hyena";

 An array contains a set of data represented by a single variable name  A “list” of values 3 $animals[] “ostrich” “anteater” “orangutan” “cheetah” “hyena” $animals[] = "ostrich"; $animals[] = "anteater"; $animals[] = "orangutan"; $animals[] = "cheetah"; $animals[] = "hyena";

 An element refers to a piece of data stored in an array  An index is an element’s numeric position within the array By default, indexes start with zero (0) An array element is referenced by enclosing its index in brackets after the array name: print $animals[0]; 4

 PHP has a number of built-in arrays  Example: $_SERVER  Also called autoglobal arrays $_SERVER $_POST $_GET $_COOKIE $_SESSION 5

 Use print_r to quickly display array contents  Not useful for user output 6 <?php print_r($_SERVER); ?> <?php print " "; print_r($_SERVER); print " "; ?> Much prettier

$array_name = array(values); 7 $animals[] = "ostrich"; $animals[] = "anteater"; $animals[] = "orangutan"; $animals[] = "cheetah"; $animals[] = "hyena"; – OR – $animals = array("ostrich", "anteater", "orangutan", "cheetah", "hyena");

for ($i=0; $i<sizeof($animals); $i++) { print $animals[$i]. " "; //print "{$animals[$i]} "; } ostrich anteater orangutan cheetah hyena ostrich anteater orangutan cheetah hyena

 Used to loop through the elements in an array  Does not require a counter  Syntax: foreach ($array_name as $variable_name) { statements; } 9

foreach ($animals as $animal) { print "$animal "; } 10

 Create an array called $names that contains the names of 5 of your classmates  Print the array using print_r  Print the first name in the array  Print the last name in the array  Print the array using a for loop  Print the array using a for-each loop

12PHP Programming with MySQL  With associative arrays, you specify an element’s key by using the array operator (=>)  Syntax : $array_name = array(key=>value,...);

13PHP Programming with MySQL $capitals = array("Texas" => "Austen", "Oregon" => "Salem", "Ohio" => "Columbus", "New York" => "Albany"); print "The capital of Texas is ". $capitals['Texas']; print "The capital of Texas is {$capitals['Texas']}"; The capital of Texas is Austen

14PHP Programming with MySQL $capitals = array("Texas" => "Austen", "Oregon" => "Salem", "Ohio" => "Columbus", "New York" => "Albany"); foreach ($capitals as $state => $capital) { print "The capital of $state is $capital. "; } The capital of Texas is Austen. The capital of Oregon is Salem. The capital of Ohio is Columbus. The capital of New York is Albany. The capital of Texas is Austen. The capital of Oregon is Salem. The capital of Ohio is Columbus. The capital of New York is Albany.

 Use count() or sizeof() to find the total number of elements in an array 15 $capitals = array("Texas" => "Austen", "Oregon" => "Portland", "Ohio" => "Columbus", "New York" => "Albany"); echo "There are ". count($capitals). " capitals."; There are 4 capitals.

 str_split() and explode() functions split a string into an array str_split() uses a length argument to represent the number of characters to assign to each array element $array = str_split(string[, length]); explode() splits a string at a specified separator $array = explode(separators, string); 16

$months = "JanFebMarApr"; $month_array = str_split($months, 3); foreach($month_array as $month) echo "$month "; *Note that each element must have the same length 17

$animals = "ostrich,anteater, orangutan,cheetah,hyena"; $animal_array = explode(",", $animals); foreach ($animal_array as $animal) echo "$animal "; 18 ostrich anteater orangutan cheetah hyena ostrich anteater orangutan cheetah hyena  Use the explode() function to convert a string to an array  $array = explode(separators, string);  If the string does not contain the specified separators, the entire string is assigned to the first element of the array

19  Use the implode() function to convert an array to a string  $variable = implode(separators, array);  If the string does not contain the specified separators, the entire string is assigned to the first element of the array $presArray = array("George W. Bush", "William Clinton", "George H.W. Bush", "Ronald Reagan", "Jimmy Carter"); $presidents = implode(", ", $presArray); echo $presidents;

20PHP Programming with MySQL  array_shift() 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 Pass the name of an array followed by comma-separated values for each element you want to add

21PHP Programming with MySQL $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);

22PHP Programming with MySQL  array_pop() removes the last element from the end of an array  array_push() 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

23PHP Programming with MySQL $HospitalDepts = array( “Anesthesia”, “Molecular Biology”, “Neurology”, “Pediatrics”); array_pop($HospitalDepts); array_push($HospitalDepts, “Psychiatry”, “Pulmonary Diseases”); Anesthesia Molecular Biology Neurology Psychiatry Pulmonary Diseases Anesthesia Molecular Biology Neurology Psychiatry Pulmonary Diseases

24PHP Programming with MySQL  The unset() function removes array elements Pass the array name and the index number of the element you want to remove  unset($HospitalDepts[1]);  unset($HospitalDepts[1], $HospitalDepts[2]);  The array_values() function renumbers an indexed array’s elements

 Make the following modifications to your $names array, and print the array after each step: 1. add a name to the beginning of the array 2. add two names to the end of the array 3. remove the first array element 4. remove the third array element

26PHP Programming with MySQL  The array_unique() function removes duplicate elements from an array Pass the array name

27PHP Programming with MySQL $topGolfers = array( "Tiger Woods", "Tiger Woods", "Vijay Singh”, "Vijay Singh", "Ernie Els", "Phil Mickelson","Retief Goosen", "Padraig Harrington", "David Toms", "Sergio Garcia", "Adam Scott", "Stewart Cink"); echo "The world's top golfers are: ”; $topGolfers = array_unique($topGolfers); foreach ($topGolfers as $golfer) { echo "$golfer "; } echo " ";

28PHP Programming with MySQL  in_array() returns Boolean TRUE if a given value exists in an array  array_search() 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."; }

29PHP Programming with MySQL  array_key_exists determines whether a given index or key exists  array_key_exists($search_key, $array) $GamePieces["Dancer"] = "Daryl"; $GamePieces["Fat Man"] = "Dennis"; $GamePieces["Assassin"] = "Jennifer"; if (array_key_exists("Fat Man", $GamePieces)) { echo "{$GamePieces["Fat Man"]} is 'Fat Man'."; }

30PHP Programming with MySQL $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'. ”; }

31PHP Programming with MySQL  The most commonly used array sorting functions are: sort() and rsort() for indexed arrays ksort() and krsort() for associative arrays

32PHP Programming with MySQL sort() rsort()

 Display your $names array in alphabetical order  Display your $names array in reverse alphabetical order

34PHP Programming with MySQL  To merge two or more arrays use the array_merge() function  Syntax: new_array = array_merge($array1, $array2, $array3,...);

PHP Programming with MySQL 35 $mammals = array("cat", "dog", "bear"); $reptiles = array("snake", "lizard"); $birds = array("emu", "parakeet", "canary"); $animals = array_merge($mammals, $reptiles, $birds); print_r($animals); $mammals = array("cat", "dog", "bear"); $reptiles = array("snake", "lizard"); $birds = array("emu", "parakeet", "canary"); $animals = array_merge($mammals, $reptiles, $birds); print_r($animals); Array ( [0] => cat [1] => dog [2] => bear [3] => snake [4] => lizard [5] => emu [6] => parakeet [7] => canary ) Array ( [0] => cat [1] => dog [2] => bear [3] => snake [4] => lizard [5] => emu [6] => parakeet [7] => canary )

 Create a second array called $family_names.  Add at least three names to the array.  Merge $names and $family_names into an array called $all_names.  Remove any duplicates from $all_names.  Print $all_names.

37PHP Programming with MySQL  array_shift() removes the first element from the beginning of an array  array_unshift() adds one or more elements to the beginning of an array  array_pop() removes the last element from the end of an array  array_push() adds one or more elements to the end of an array

38PHP Programming with MySQL  unset() removes array elements  array_unique() removes duplicate elements from an array  in_array() returns a Boolean value of true if a given value exists in an array  array_search() determines whether a given value exists in an array  array_key_exists() determines whether a given index or key exists