PHP Using Arrays.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
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.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Arrays.
Arrays, A1 COMP 401, Fall 2014 Lecture 4 8/28/2014.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
PHP Introduction.
Programming with Collections Collections in Java Using Arrays Week 9.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
 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.
Computer Science II Exam I Review Monday, February 6, 2006.
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
Guide To UNIX Using Linux Third Edition
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Java Unit 9: Arrays Declaring and Processing Arrays.
Lists in Python.
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
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.
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,
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Chapter 8: Arrays.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
Class 2Intro to Databases Goals of this class Include & Require in PHP Generating Random Numbers in PHP Arrays – Numerically Indexed and Associative Program.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 174: Web Programming September 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
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 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
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.
5 1 Data Files CGI/Perl Programming By Diane Zak.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
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.
Max(), with an array argument, returns the largest value in the array  With several numerical arguments, it returns the largest argument E.g., $arr =
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
11 – Introduction to PHP(1) Informatics Department Parahyangan Catholic University.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Introduction to programming in java Lecture 21 Arrays – Part 1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Lesson 3 Functions. Lesson 3 Functions are declared with function. For example, to calculate the cube of a number function function name (parameters)
String and Lists Dr. José M. Reyes Álamo.
CS 371 Web Application Programming
Containers and Lists CIS 40 – Introduction to Programming in Python
Java Primer 1: Types, Classes and Operators
Arrays in PHP are quite versatile
Chapter 7 Arrays.
Topics Introduction to File Input and Output
Object Oriented Programming in java
String and Lists Dr. José M. Reyes Álamo.
MSIS 655 Advanced Business Applications Programming
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Web Programming– UFCFB Lecture 21
PHP an introduction.
Topics Introduction to File Input and Output
Presentation transcript:

PHP Using Arrays

Arrays Topics: Numerically indexed arrays Non-numerically indexed arrays (hashes, associative arrays) Array operators Multidimensional arrays - read Array sorting Other array functions Complete reference for arrays at http://www.php.net/array

Arrays An array = a set of data represented by a single variable name Example, the $products array: In PHP, each array element consists of : A value A key or index that is used to access the element (internally, all arrays in PHP are associative = hashes…) The keys / indexes can be: Non-negative integers → these PHP arrays have the logical structure similar to a classic array in other languages (Java, C) and can be used in the traditional way Strings → associative arrays or hashes Mixture of both

Creating Numerically Indexed Arrays Create a numerically-indexed (shortly indexed) array with the language construct array: Syntax: $array_name = array(values); Examples: $products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’); $list = array(2, 4, 6, 8); Keys are automatically 0, 1, 2 etc. Note: $array_name = array(); creates an empty array

Creating Numerically Indexed Arrays Create an indexed array by assigning a value to an element of an array that doesn’t exist (the array!): $array_name[index] = value; or $array_name[] = value; Writing to an indexed array with empty [ ] creates the new element at end of the array  PHP arrays don’t have fixed length! Example: $list = array(2, 4, 6, 8); $list[ ] = 10;  $list is now array(2, 4, 6, 8, 10) $Provinces[] = "Newfoundland and Labrador"; $Provinces[] = "Prince Edward Island"; if $Provinces didn’t exist before, it is created and has 2 elements, indexed 0 and 1.

Creating Numerically Indexed Arrays Other ways to create indexed arrays: $new_array = $existing_array; // as a single unit The range(…) function creates an array with a range of values Can be used with either numbers or characters (single letters) $n = range(4, 7); is same as $n = array(4, 5, 6, 7); $c = range(‘p’, ‘s’); is same as $c = array(‘p’, ‘q’, ‘r’, ‘s’); A third parameter allows to specify a step size between values: $odds = range(1, 10, 2); creates an array containing (1, 3, 5, 7, 9) Load an array contents directly from a file Load an array contents directly from a database Functions to extract parts of an array or reorder an array

Creating Associative Arrays (Hashes) Create an associative array with the language construct array: $prices = array(‘Tires’ => 100, ‘Oil’ => 10, ‘Spark Plugs’ => 4); $hash = array(‘QB’ => “Palmer”, ‘WR’ => “OchoCinco”, …); After first keys, if you don’t supply more, you get numeric keys starting from 0: $mixed = array('QB' => "Palmer", 'WR' => OchoCinco', 'Smith', 'Williamson');  'Smith‘ is indexed 0, 'Williamson‘ is indexed 1 Create an associative array by assigning a value to an element of an array that doesn’t exist (the array!): $prices[‘Tires’] = 100; $prices[‘Oil’] = 10; $prices[‘Spark Plugs’] = 4;

Accessing Array Contents Use array name plus the index / key in square brackets to access array elements. $Provinces[0] $prices[‘Tires’] or $prices[“Tires”] The quotes around the string keys are optional for single-word keys (a warning might be generated), but generally are used However, quotes cannot be used when interpolating an element of an array; solutions: Don’t rely on interpolation, e.g. use instead regular string concatenation: echo “The price for tires is”. $prices[‘Tires’]; Omit quotes: e.g. echo “The price for tires is $prices[Tires]”;

Creating Arrays http://cscdb.nku.edu/csc301/frank/PHP_Arrays/arrays_creating.php

Accessing Array Contents Read/modify an array element’s value as usual Writing to array with a currently-undefined key (or beyond the end of an indexed array) creates a new element. Use the unset(…) function to eliminate: An array: $products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’); unset($products); // $products doesn’t exist after this statement An array element: unset($products[0]); // $products remains with 2 elements only, indexed 1 and 2

Sequential Access to Array Elements Logical internal structure of arrays: elements are stored in a linked list of cells; each cell includes both the key and the value of the element; cells are linked in the order they are created - numerically indexed arrays too  classic arrays are ordered by index, PHP arrays are ordered by creation order  array elements can be can accessed in creation order or key order if keys are numbers

Sequential Access to Array Elements Regular for loops for numerically indexed arrays: $products = array('Tires', 'Oil', 'Spark Plugs'); for ($i=0; $i<3; $i++) { echo $products[$i] . ", "; }

Sequential Access to Array Elements Foreach loops, specially designed for arrays, can be used for all types of indexes. For numerically indexed arrays, use: foreach($arrayName as $val) $val steps through each of the values in $arrayName For associative arrays, you can also use: foreach($arrayName as $key => $val) $key and $val are set to each key - value in the hash in turn (in the defined order = creation order)

Sequential Access to Array Elements Foreach loops, examples: $products = array('Tires', 'Oil', 'Spark Plugs'); foreach ($products as $val) { echo $val . ", "; } $prices = array('Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4); foreach ($prices as $key => $val) { echo "$key - $val, ";

Sequential Access to Array Elements Important - to modify the array elements’ values in a foreach loop, use the reference operator: $prices = array('Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4); foreach ($prices as $key => &$val) { $val *= 1.05; // increases product prices by 5% } By using &, $val will successively be an alias (alternative name) for each array element value, instead of being a separate variable that holds a copy of the array element value!

Sequential Access to Array Elements Each array has an internal pointer (or marker) that references one element in the array → called current pointer Various functions exist to (in)directly manipulate this pointer to navigate in the array: reset($a) sets the current element of array $a to the start of the array; returns $a’s first element end($a) sends the pointer to the end of the array $a; returns last array element current($a) or pos($a) return the array element pointed to by the current pointer next($a) and each($a) advance the pointer forward one element; return the current element before (each) / after (next) advancing the pointer prev($a) is the opposite of next()

Array Operators Most of them have an analogue in the scalar operators, but with a different meaning! + $a + $b performs the union of $a and $b arrays; $b is appended to $a, except for $b’s elements that have the same keys as some elements already in $a, which are not added = = $a ==$b is true if $a and $b contain the same elements = = = $a ==$b is true if $a and $b contain the same elements, with the same type, in the same order != $a !=$b is true if $a and $b do NOT contain the same elements <> Same as != != = $a !==$b is true if $a and $b do NOT contain the same elements, with the same type, in the same order

Size of an Array Two functions get the number of elements of an array passed to them; return 0 for an empty array and 1 for a scalar variable: count($a ) sizeof($a) array_count_values($array_name) returns an associative array with: keys = the distinct values from $array_name the value for each key is the number of times that key occurs in $array_name Example: $list = array(1, 2, 6, 6, 6, 2); $c = count($list); // $c contains 6 $ac = array_count_values($list);// $ac contains 1=>1, 2=>2, 6=>3

Sorting Arrays 3 types of sort: Indexed array – sort values and reset indexes Hash – sort by values Hash – sort by keys 3 ways to sort (function names follow above order): Ascending – sort( ), asort( ), ksort( ) Descending – rsort( ), arsort( ), krsort( ) User-defined – usort( ), uasort( ), uksort( )

Sorting Arrays The ascending and descending sort routines are just called with the array name ascending/descending sort() also take an optional argument that specifies the sort type: SORT_REGULAR (the default; alphabetically for strings, numeric order for numbers), SORT_NUMERIC, or SORT_STRING They sort the original array User-defined sort takes second argument The name of a function that returns <0, 0 or >0 given 2 input arguments based on their relative order (<0 means 1st is less than 2nd)

Arrays Sorting http://cscdb.nku.edu/csc301/frank/PHP_Arrays/arrays_sorting.php

Loading Arrays from Files Recall that file($file_name) returns the entire file content as an array: each line in the file is one element of this array. A line can be split into fields using array explode(string $separator, string $line_string [, int $limit]) Ex: $s = "15:42, 20th April\t4 tires\t1 oil\t6 spark plugs\t$434.00\t22 4th St, Troy"; $a = explode (“\t”, $s); // $s is exploded into: "15:42, 20th April", "4 tires", "1 oil", "6 spark plugs", // "$434.00", and "22 4th St, Troy", which are stored in the array $a The optional limit parameter can be used to limit the number of parts returned Opposite for explode(): string implode(string $separator, array $arr) it combines an array’s elements’ values into a single string, separated by the specified separator