1 arrays in php php functions. 2 array definition an array is a complex variable that enables you to...

27
1 Arrays in PHP PHP Functions

Upload: junior-anderson

Post on 17-Dec-2015

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

1

Arrays in PHPPHP Functions

Page 2: 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

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.

Page 3: 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

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.

Page 4: 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

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.

Page 5: 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

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.

Page 6: 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

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);

Page 7: 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

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'; ?>

Page 8: 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

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'; ?>

Page 9: 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

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'; ?>

Page 10: 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

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:

<html> <head></head> <body> Today's shopping list: <ul> <?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 "<li>$shoppingList[$x]"; } ?> </ul> </body> </html>

Page 11: 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

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.

Page 12: 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

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.

Page 13: 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

13

Processing Arrays With loops (The foreach() Loop)

To better understand how this works, rewrite the previous example using the foreach() loop:

<html> <head></head> <body> Today's shopping list: <ul> <?php // define array $shoppingList = array('eye of newt', 'wing of bat', 'tail of frog'); // loop over it foreach ($shoppingList as $item) { echo "<li>$item"; } ?> </ul> </body> </html>

Page 14: 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

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:

<html> <head></head> <body> I can see: <ul> <?php // define associative array $animals = array ('dog' => 'Tipsy', 'cat' => 'Tabitha','parrot' => 'Polly'); // iterate over it foreach ($animals as $key => $value) { echo "<li>a $key named $value"; } ?> </ul> </body> </html>

Page 15: 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

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.

Page 16: 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

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(); ?>

Page 17: 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

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.

Page 18: 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

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.

Page 19: 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

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:

Page 20: 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

20

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

// invoke a function // pass it a single argument convertMilesToKilometres(50); ?>

Page 21: 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

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); ?>

Page 22: 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

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.

Page 23: 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

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.

Page 24: 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

24

A Function with Optional Argument <?php function fontwrap($txt, $size=3) { print ”<font size= \“$size \”face

= \“Helvetica, Arial, Sans-Serif \”>$txt</font>”; } fontwrap (“A heading<br>”,5); fontwrap (“some body text<br>”); ?>

Page 25: 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

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 ?>

Page 26: 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

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.

Page 27: 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

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

?>