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.

Slides:



Advertisements
Similar presentations
Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Advertisements

C Language.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Objectives Using functions to organize PHP code
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
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";
ITC 240: Web Application Programming
PHP Functions Composite Types. Functions  Declaration  function functionName(paramList) {  /* code goes here */ }  paramList is comma-separated list.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 7 Manipulating Arrays PHP Programming with MySQL.
Chapter 8 Arrays and Strings
1 CS428 Web Engineering Lecture 19 Data Types (PHP - II)
PhP Tutorial (3). Working with Arrays – Strings in PHP What is an Array.
Strings and Arrays. String Is a sequence of characters. Example: “hello”, “how are you?”, “123”,and are all valid string values.
CSE 154 LECTURE 6: EMBEDDED PHP. PHP syntax template HTML content HTML content HTML content... PHP any contents of.
PHP Arrays. Outline o What is array in PHP ? o Numeric array o Associative array o Multidimensional array.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
Lists in Python.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
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.
Week 9 PHP Cookies and Session Introduction to JavaScript.
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.
Chapter 8 Arrays and Strings
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
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.
Arrays. Indexed Arrays Use numbers as keys: $grades = array(); $grades[0] = ' A ' ; $grades[1] = ' A- ' ; $grades[2] = ' B+ ' ; Or with one statement:
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
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.
Advanced Computer Science Lesson 4: Reviewing Loops and Arrays Reading User Input.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Max(), with an array argument, returns the largest value in the array  With several numerical arguments, it returns the largest argument E.g., $arr =
 Variables can store data of different types, and different data types can do different things.  PHP supports the following data types:  String  Integer.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
NMD202 Web Scripting Week2. Web site
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
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.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Lesson 3 Functions. Lesson 3 Functions are declared with function. For example, to calculate the cube of a number function function name (parameters)
Web Design 2 Using PHP PHP Arrays.
Data types: Complex types (List)
Working with Collections of Data
Containers and Lists CIS 40 – Introduction to Programming in Python
Arrays in PHP are quite versatile
Arrays An array in PHP is an ordered map
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
Objectives Create an array Work with array properties and methods
Arrays Arrays A few types Structures of related data items
PHP an introduction.
Presentation transcript:

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 every element – Values get associated to keys – Arrays specified as key-value pairs Effectively an ordered map

Arrays (cont’d) Initialization can be done in different ways Ex: array( key => value, key2 => value2, key3 => value3,... ) – Comma after the last element is optional and may not be used The key is usually an Integer or a String The value can be of any data type

Arrays (cont’d) // On earlier versions “value1", “key2" => “value2", ); // PHP 5.4 onwards $array = [ “key1" => “value1", “key2" => “value2", ]; ?>

Arrays (cont’d) If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten Input – “x", 1.7 => “y", "1" => “z" ); ?> Output – array(1) { [1]=> string(1) “z" }

Arrays (cont’d) Useful in passing messages across webpages – Used to pass around session variables using named keys If no index is specified, then the default indexing starts at 0 (integer) and then counts upwards as one keeps adding elements to the array

Arrays (cont’d) $first = array(); $first[‘size'] = ‘big'; $first[‘shape'] = ‘cubic'; $first[‘density'] = ‘high'; $first[‘type'] = ‘compound'; $first[] = 100; // $first[0]=100; $second = array(); $second[] = ‘x'; $second[] = ‘y'; $second[] = ‘z'; // Result of the above: // $first = array('size' => 'big', 'shape' => 'cubic', 'density' => 'high ', 'type' => 'compound', '0' => 100) // $second = array(0 => 'x‘, 1 => 'y', 2 => 'z')

Array (cont’d) $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?>

Array (cont’d) By default, arrays are 0-index based But, one can set 1-index based arrays 'January', 'February', 'March'); print_r($firstquarter); ?> Output array ( [1] => 'January' [2] => 'February' [3] => 'March' )

Array (cont’d) Arrays can be sorted with inbuilt commands

Array (cont’d) Arrays can have any content inside them – Hence, arrays can contain arrays – This leads to creation of multidimensional and recursive arrays array ( "a" => "orange", "b" => "banana", "c" => "apple"),"numbers" => array ( 1, 2, 3, 4, 5, 6), "holes" => array ( "first", 5 => "second", "third")); // Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]); // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good"; ?>

Array (cont’d) Array assignment involves copying one array into the other Involves value-copying –

Array (cont’d) The array_diff() function compares array values two or more arrays – Returns an array with the keys and values from the first array, only if the value is not present in any of the other arrays – Only the value is used for the comparison, not the key – "Cat",1=>"Dog",2=>"Horse"); $a2=array(3=>"Horse",4=>"Dog",5=>"Fish"); print_r(array_diff($a1,$a2)); ?> – Output: Array ( [0] => Cat ) General syntax: array_diff(array1,array2,array3...)

Array (cont’d) The array_diff_assoc() function compares two or more arrays – Returns an array with the keys and values from the first array, only if they are not present in any of the other arrays – Uses both the keys and the values for comparison – "Cat",1=>"Dog",2=>"Horse"); $a2=array(0=>"Rat",1=>"Horse",2=>"Dog"); $a3=array(0=>"Horse",1=>"Dog",2=>"Cat"); print_r(array_diff_assoc($a1,$a2,$a3)); ?> – Output: Array ( [0] => Cat [2] => Horse ) General syntax: array_diff_assoc(array1,array2,array3...)

Array (cont’d) The array_combine() function creates an array by combining two other arrays – The first array is the keys – The second array is the values General syntax: array_combine(array1,array2) Output: Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow )

Array (cont’d) The array_filter() function passes each value in the array to a user-made function – The user-made function returns either true or false – The array_filter() returns an array only with the values that returned true – "Dog",1=>"Cat",2=>"Horse"); print_r(array_filter($a,"myfunction")); ?> – Output: Array ( [2] => Horse )

Array (cont’d) The array_intersect() function compares two or more arrays – Returns an array with the keys and values from the first array, only if the value is present in all of the other arrays – "Cat",1=>"Dog",2=>"Horse"); $a2=array(3=>"Horse",4=>"Dog",5=>"Fish"); print_r(array_intersect($a1,$a2)); ?> – Output: Array ( [1] => Dog [2] => Horse )

Array (cont’d) The array_key_exists() function checks an array for a specified key – Returns true if the key exists – Returns false if the key does not exist – "Dog","b"=>"Cat"); if (array_key_exists("a",$a)) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?> – Output: Key exists!

Array (cont’d) The array_merge() function merges one or more arrays into one array – "Horse","b"=>"Dog"); $a2=array("c"=>"Cow","b"=>"Cat"); print_r(array_merge($a1,$a2)); ?> – Output: Array ( [a] => Horse [b] => Cat [c] => Cow ) Can use array_merge() with only one parameter

Array (cont’d) The array_merge_recursive() function merges one ore more arrays into one array The difference between this function and the array_merge() function is when two or more array elements have the same key, instead of override the keys, the array_merge_recursivse() function makes the value as an array Sample code: – "Horse","b"=>"Dog"); $a2=array("c"=>"Cow","b"=>"Cat"); print_r(array_merge_recursive($a1,$a2)); ?> – Output: Array ( [a] => Horse [b] => Array ( [0] => Dog [1] => Cat ) [c] => Cow )

Array (cont’d) The array_pop() function deletes the last element of an array – – Output: Array ( [0] => Dog [1] => Cat ) – General syntax: array_pop(array)

Array (cont’d) The array_reverse() function returns an array in the reverse order – "Dog","b"=>"Cat","c"=>"Horse"); print_r(array_reverse($a)); ?> – Output: Array ( [c] => Horse [b] => Cat [a] => Dog )

Array (cont’d) The array_shift() function removes the first element from an array – Returns the value of the removed element – "Dog","b"=>"Cat","c"=>"Horse"); echo array_shift($a); print_r ($a); ?> – Output: Dog Array ( [b] => Cat [c] => Horse ) – If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 – "Dog",1=>"Cat",2=>"Horse"); echo array_shift($a); print_r ($a); ?> – Output: Dog Array ( [0] => Cat [1] => Horse )

Array (cont’d) The array_walk() function runs each array element in a user-made function – The array's keys and values are parameters in the function – Returns True or False – "; } $a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse"); array_walk($a,"myfunction"); ?> – Output: The key a has the value Cat The key b has the value Dog The key c has the value Horse

Array (cont’d) The asort() function sorts an array by the values – Values keep their original keys – Returns TRUE on success, or FALSE on failure – "Dog", "b" => "Cat", "c" => "Horse"); asort($my_array); print_r($my_array); ?> – Output: Array ( [b] => Cat [a] => Dog [c] => Horse )

Array (cont’d) The arsort() function sorts an array by the values in reverse order – Values keep their original keys. – Returns TRUE on success, or FALSE on failure – "Dog", "b" => "Cat", "c" => "Horse"); arsort($my_array); print_r($my_array); ?> – Output: Array ( [c] => Horse [a] => Dog [b] => Cat )

Array (cont’d) The array_values() function returns an array containing all the values of an array – "Cat","b"=>"Dog","c"=>"Horse"); print_r(array_values($a)); ?> – Output: Array ( [0] => Cat [1] => Dog [2] => Horse )

Array (cont’d) The array_sum() function returns the sum of all the values in the array – "5",1=>"15",2=>"25"); echo array_sum($a); ?> – Output: 45

Array (cont’d) The explode() function breaks a string into an array – General syntax: explode(separator,string,limit) – – Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )

Array (cont’d) The implode() function returns a string from the elements of an array – General syntax: implode(separator,array) The separator parameter is optional these days, but recommended to use for backward compatibility – – Output: Hello World! Beautiful Day!