1 Arrays in PHP PHP Functions. 2 Array Definition An array is a complex variable that enables you to store multiple values in a single variable; It comes.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
References and Data Structures. References Just as in C, you can create a variable that is a reference (or pointer) to another variable. That is, it contains.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
Objectives Using functions to organize PHP code
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Introduction to C Programming
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
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
Chapter 14: Overloading and Templates
VBA Modules, Functions, Variables, and Constants
Hashes a “hash” is another fundamental data structure, like scalars and arrays. Hashes are sometimes called “associative arrays”. Basically, a hash associates.
Chapter 6: User-Defined Functions I
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
Scripting Languages Perl Chapter #4 Subroutines. Writing your own Functions Functions is a programming language serve tow purposes: –They allow you to.
Chapter 6: User-Defined Functions I
Introduction to C Programming
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Introduction to JavaScript for Python Programmers
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Java Unit 9: Arrays Declaring and Processing Arrays.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
Arrays – What is it? – Creation – Changing the contents Functions – What is it? – Syntax – How they work – Anonymous functions A quick lesson in Objects.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
4 1 Array and Hash Variables CGI/Perl Programming By Diane Zak.
Linux+ Guide to Linux Certification, Third Edition
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Functions Lecfture Abstraction abstraction is the process of ignoring minutiae and focusing on the big picture in modern life, we are constantly.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays.
Learners Support Publications Classes and Objects.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
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.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
PHP Constructs Advance Database Management Systems Lab no.3.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
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.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
CONTENTS Processing structures and commands Control structures – Sequence Sequence – Selection Selection – Iteration Iteration Naming conventions – File.
JavaScript, Fourth Edition
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Perl Day 5. Arrays vs Hash Arrays are one way to store multiple things in a variable. Hashes are another. Arrays are one way to store multiple things.
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
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,
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.
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.
SQL Triggers, Functions & Stored Procedures Programming Operations.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Linux Administration Working with the BASH Shell.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Session 2 Basics of PHP.
Chapter 9: Value-Returning Functions
Arrays An array in PHP is an ordered map
User-Defined Functions
Presentation transcript:

1 Arrays in PHP PHP Functions

2 Array Definition An array is a complex variable that enables you to store multiple values in a single variable; It comes in handy when you need to store and represent related information. An array variable can best be thought of as a “container” variable, which can contain one or more values.

3 Array Definition Here is an example: <?php // define an array $flavors = array('strawberry', 'grape','vanilla', 'caramel', 'chocolate'); ?> Here, $flavors is an array variable, which contains the values strawberry, grape, vanilla, caramel, and chocolate. The various elements of the array are accessed via an index number, with the first element starting at zero. So, to access the value grape, use the notation $flavors[1], while chocolate would be $flavors[4] * Basically, the array variable name followed by the index number in square braces.

4 Array Definition PHP also enables you to replace indices with user-defined “keys” to create a slightly different type of array. Each key is unique, and corresponds to a single value within the array. Keys may be made up of any string of characters, including control characters.

5 Array Definition <?php // define associative array $fruits = array('red' => 'apple', 'yellow' => 'banana', 'purple' => 'plum', 'green' => 'grape'); ?> In this case, $fruits is an array variable containing four key-value pairs. The => symbol is used to indicate the association between a key and its value. To access the value banana, use the notation $fruits['yellow'], while the value grape would be accessible via the notation $fruits['green']. This type of array is sometimes referred to as a hash or associative array.

6 Array Definition If you want to look inside an array, head straight for the print_r() function, which X-rays the contents of any PHP variable or structure. Here: print_r($fruits);

7 Creating an Array To define an array variable, name it using standard PHP variable naming rules and populate it with elements using the array() function, as illustrated in the following: <?php // define an array $flavors = array('strawberry', 'grape','vanilla', 'caramel', 'chocolate'); ?> An alternative way to define an array is by specifying values for each element using index notation, like this: <?php // define an array $flavors[0] = 'strawberry'; $flavors[1] = 'grape'; $flavors[2] = 'vanilla'; $flavors[3] = 'caramel'; $flavors[4] = 'chocolate'; ?>

8 Creating an Array To create an associative array, use keys instead of numeric indices: <?php // define an associative array $fruits['red'] = 'apple'; $fruits['yellow'] = 'banana'; $fruits['purple'] = 'plum'; $fruits['green'] = 'grape'; ?>

9 Modifying Array Elements To add an element to an array, assign a value using the next available index number or key: <?php // add an element to a numeric array whose last index is 4 $flavors[5] = 'mango'; // if you don't know the next available index // this will also work $flavors[] = 'mango'; // add an element to an associative array $fruits['pink'] = 'peach'; ?> To modify an element of an array, assign a new value to the corresponding scalar variable. If you want to replace the flavor “strawberry” with “blueberry” in the $flavors array created previously, you’d use the following: <?php // modify an array $flavors[0] = 'blueberry'; ?>

10 Processing Arrays With loops To iteratively process the data in a PHP array, loop over it using any of the loop constructs discussed earlier. To better understand this, create and run the following script: Today's shopping list: <?php // define array $shoppingList = array('eye of newt', 'wing of bat', 'tail of frog'); // loop over it // print array elements for ($x = 0; $x < sizeof($shoppingList); $x++) { echo " $shoppingList[$x]"; } ?>

11 Processing Arrays With loops Here, the for() loop is used to iterate through the array, extract the elements from it using index notation, and display them one after the other in an unordered list. Note the sizeof() function used in the previous script. This function is one of the most important and commonly used array functions, and it returns the size of (number of elements within) the array. The sizeof() function is mostly used in loop counters to ensure that the loop iterates as many times as there are elements in the array.

12 Processing Arrays With loops (The foreach() Loop) This loop(foreach) runs once for each element of the array, moving forward through the array on each iteration. On each run, the statements within the curly braces are executed, and the currently selected array element is made available through a temporary loop variable. Unlike a for() loop, a foreach() loop doesn’t need a counter or a call to sizeof(); it keeps track of its position in the array automatically.

13 Processing Arrays With loops (The foreach() Loop) To better understand how this works, rewrite the previous example using the foreach() loop: Today's shopping list: <?php // define array $shoppingList = array('eye of newt', 'wing of bat', 'tail of frog'); // loop over it foreach ($shoppingList as $item) { echo " $item"; } ?>

14 Processing Arrays With loops (The foreach() Loop) You can process an associative array with a foreach() loop as well, although the manner in which the temporary variable is constructed is a little different to accommodate the key-value pairs. Try the following script to see how this works: I can see: <?php // define associative array $animals = array ('dog' => 'Tipsy', 'cat' => 'Tabitha','parrot' => 'Polly'); // iterate over it foreach ($animals as $key => $value) { echo " a $key named $value"; } ?>

15 Creating User Defined Functions A function is simply a set of program statements that perform a specific task, and that can be called, or executed, from anywhere in your program. Every programming language comes with its own functions, and typically also enables developers to define their own.

16 Defining and Invoking functions To understand how custom functions work, examine the following script: <?php // define a function function displayShakespeareQuote() { echo 'Some are born great, some achieve greatness, and some have greatness thrust upon them'; } // invoke a function displayShakespeareQuote(); ?>

17 Defining and Invoking functions In PHP, functions are defined using the special function keyword. This keyword is followed by the name of the function (which must conform to the standard naming rules for variables in PHP), a list of arguments (optional) in parentheses, and the function code itself, enclosed in curly braces. This function code can be any legal PHP code—it can contain loops, conditional statements,or calls to other functions. In the previous example, the function is named displayShakespeareQuote() and only contains a call to PHP’s echo() function. Calling a user-defined function is identical to calling a built-in PHP function like isset() or die()—simply invoke it by using its name. If the function is designed to accept input values, the values can be passed to it during invocation in parentheses. In PHP 3.x, functions could only be invoked after they had been defined. In PHP 4.x and PHP 5.x, functions can be invoked even if their definitions appear further down in the program.

18 Using Arguments and Return Values Because functions are supposed to be reusable code fragments, it doesn’t make sense for them to always return the same value. Thus, it is possible to create functions that accept different values from the main program and operate on those values to return different, more pertinent results on each invocation. These values are called arguments, and they add a whole new level of power and flexibility to your code.

19 Using Arguments and Return Values Typically, you tell your function which arguments it can accept through an argument list (one or more variables) in the function definition. When a function is invoked with arguments, the variables in the argument list are replaced with the actual values passed to the function and manipulated by the statements inside the function block to obtain the desired result. To illustrate, consider the next example, which uses a function with a singleargument list. Depending on the value passed to the function, conversion is performed between two different measurement scales:

20 Using Arguments and Return Values <?php // define a function // with a single-argument list function convertMilesToKilometres($miles) { echo "$miles miles = ". $miles * " km"; } // invoke a function // pass it a single argument convertMilesToKilometres(50); ?>

21 Using Arguments and Return Values Usually, when a function is invoked, it generates a return value. This return value is explicitly set within the function with the return statement. To see how this works, consider the following example: <?php // define a function function getTriangleArea($base, $height) { $area = $base * $height * 0.5; return $area; } // invoke a function echo 'The area of a triangle with base 10 and height 50 is '. getTriangleArea(10, 50); ?>

22 Using Arguments and Return Values Here, when the getTriangleArea() function is invoked with two arguments, it performs a calculation and assigns the result to the $area variable. This result is then returned to the main program through the return statement. It is important to note that when PHP encounters a return statement within a function, it stops processing the function and returns control to the statement that invoked the function.

23 Using Arguments and Return Values If you invoke a function with an incorrect number of arguments, PHP will generate a warning, but still attempt to process the function. To avoid this, either make arguments optional by setting default values for them or define your function with support for variable-length argument lists.

24 A Function with Optional Argument <?php function fontwrap($txt, $size=3) { print ” $txt ”; } fontwrap (“A heading ”,5); fontwrap (“some body text ”); ?>

25 Passing Variables to Functions By Reference It is possible to pass arguments to functions by reference. <?php Function addfive(& $num) { $num+=5; } $orignum = 10; addfive($orignum); print $orignum; // prints 15 ?>

26 Defining Global and Local Variables Unless you specify otherwise, the variables used within a function are local—that is, the values assigned, and the changes made to them, are restricted to the function space alone. This insulates function variables from the main program space, reducing the risk of variable clashes and corruption of data. To use a variable from the main program inside a function (or vice versa), use the global keyword before the variable name inside the function definition.

27 Defining Global and Local Variables The following example explains this clearly: <?php // define two variables $itemCount = 65; $employeeCount = 125; // write a function that alters the global $itemCount variable function addItems() { global $itemCount; $itemCount = $itemCount + 100; } // write a function that alters a local variable with the same name as a global variable note that the global keyword is not used function addEmployees() { $employeeCount = 2000; } echo "Initial number of items: $itemCount"; // returns 65 addItems(); echo "Items after addItems(): $itemCount"; // returns 165 echo "Initial number of employees: $employeeCount"; // returns 125 addEmployees(); echo "Employees after addEmployees(): $employeeCount"; // returns 125 ?>