• No results found

Function

In document Athena Giao Trinh Php Mysql (Page 60-76)

Functions

Keywords: function, parameter, argument, reference, value, global,

static, scope, return, null, empty, language construct.

Subjects:

4.1.

Introduction

4.2.

Syntax

4.3.

Parameter & Argument

4.4.

Useful Functions

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

61

4.1.

Introduction:

- Function is the heart of PHP programming.

- Encapsulate any piece of code in a way that it can be called again and again.

- Classify between Language constructs and Functions.

Fastest things in PHP are the language constructs.

They are highly optimized in the interpreter

Don’t require calling external libraries

Don’t call a function if there is a language construct. As an example, using a

casting operator like (int) $total is much more efficient than using the function

intval($foo)

Function calling generate considerably amount of overhead. Using a language

construct avoid

isset() and unset() are both language constructs, even though they mostly act like

functions. However calling them does not generate the function overhead.

Common language construct:



echo()



empty()



isset()



unset()



eval()



exit()



die()



include()



include_once()



require()



require_once()



return

4.2.

Syntax:

4.2.1. Create function: function name is case-intensitive.

function name() {

//your code here }

Ex:

function hello() {

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

62

echo 'Hello World'; }

hello(); // Displays "Hello World"; HeLLo(); // Displays "Hello World";

4.2.2. Return values:

- All functions in PHP return a value (event if you don't using

return

keyword, it will return

NULL

)

-

return

keyword allows you to interrupt the execution of a function and exit it.

- Ex:

function hello() {

return 'Hello World'; }

$str = hello(); // Assigns return value "Hello World" to $str echo hello(); // Displays "Hello World"

- Functions can be declared so that they return by reference, usually resource type. Ex:

function &query() {

$result = mysql_query('SELECT email FROM users'); return $result;

}

4.3.

Parameter & Argument:

4.3.1. Different between Parameter and Argument:

- The term parameter refers to any declaration within the parentheses following the function

name in a function declaration or definition; the term argument refers to any expression

within the parentheses of a function call.

- This example demonstrates the difference between a parameter and an argument:

// $var is a parameter function test($var) {

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

63

foo(5, 'a'); //5 and 'a' are arguments return 0;

}

4.3.2. Passing by value: by default, function arguments are passed by value (so that if the

value of the argument within the function is changed, it does not get changed outside of

the function). Ex:

function myFunc($str) { $str = 'bob'; echo $str; } $str = 'jack';

myFunc($str); // Displays "bob" echo $str; // Displays 'jack'

4.3.3. Passing by reference: to allow function to modify its arguments, they must be

passed by reference.Ex:

function myFunc(&$str) { $str = 'bob'; echo $str; } $str = 'jack';

myFunc($str); // Displays "bob" echo $str; // Displays 'bob

4.3.4. Default argument values: Set default value for an argument if it's not passed to

function. Ex:

function myFunc($str = 'mother') {

echo $str; }

$str = 'jack';

myFunc($str); // Displays "jack" myFunc(); // Displays "mother"

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

64

function myFunc(&$str = 'mother') { // } $str = 'jack'; myFunc($str); echo $str;

4.3.5. Variable Scope: is the context within which it is defined. Most part all PHP

variables only have a single scope. View this script:

$a = 1; /* global scope */ function test()

{

echo $a; /* reference to local scope variable */ }

test(); // Not display "1"

4.3.5.1. Using global scope variables:

- Using

global

keyword. Ex:

$a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; // Display "3" -

Using

$GLOBALS

variable. Ex:

$a = 1; $b = 2;

function Sum() {

$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; }

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

65

Sum();

echo $b; // Display "3"

4.3.6. Static variables: A static variable exists only in a local function scope, but it does

not lose its value when program execution leaves this scope.

- Ex1:

function test() { $a = 0; echo $a; $a++; } test(); // Display "0"; test(); // Display "0";

- Ex2:

function test() { static $a = 0; echo $a; $a++; } test(); // Display "0"; test(); // Display "1";

- Note: static variable must not be declared as the result of an expression, it will cause a

parse error. Ex:

static $var = 1+2; // wrong (as it is an expression) static $var = sqrt(2); //wrong (as it is an expression)

4.4. Useful Functions:

4.4.1. func_num_args(): returns the number of arguments passed to the function.

4.4.2. func_get_arg(int $index): returns an item from the argument list.

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

66

4.4.4. function_exists(string $function_name): return TRUE if the given function

has been defined.

Chapter Exercise:

A>Write a script to calculate and return the sum of all arguments (the number of argument is

unknown) of a function.

Example: $a = calculate(1,2,3,4,6,2); // $a = 18

B>List 3 global scope variables beside $GLOBALS

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

67

Chapter 5

Array

Keywords: array, element, index, key, value, associate, sort, shuffle,

random, iteration, loop, stack, queue, pop, push, shift.

Subjects:

5.1.

Declaration

5.2.

Array Operation

5.3.

Iteration (Looping)

5.4.

Sorting

5.5.

More Functions

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

68

5.1.

Declaration:

5.1.1. Declare an array variable:

$a = array(10, 20, 30); $a = array('a' => 10, 'b' => 20, 'key' => 30); $a = array(5 => 1, 3=> 2, 1=>3, ); $a = array();

5.1.2. Array operator []:

$a[] = 10; $a['key'] = 'value';

echo $a['key']; // Displays "value"

5.1.3. Multi-dimension Arrays: element of an array is an array too. Ex:

$a = array(

array('red', 'green', 'blue'), array('small', 'medium', 'large') );

5.2.

Array Operation:

5.2.1. Printing array:

- Using

print_r()

to print only one array. Ex:

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); print_r($a); // Outputs: Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) )

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

69

- Using

var_dump()

can print more than one array.

$a = array ('a' => 'apple',

'b' => 'banana', 'c' => array ('x', 'y', 'z')); $b = array('x', 'y'); var_dump($a, $b); // Outputs: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> array(3) { [0]=> string(1) "x" [1]=> string(1) "y" [2]=> string(1) "z" } } array(2) { [0]=> string(1) "x" [1]=> string(1) "y" }

5.2.2. Counting array elements: using

count()

function. Ex:

$a = array(5,6,7);

$element = count($a); // $element will be 3

5.2.3. Checking a variable is an array: using

is_array()

function. Ex:

$a = array(5,6,7);

$result = is_array($a);

var_dump($result); // Displays "bool(true)"

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

70

- Note: if element value equal

NULL

,

isset()

still return

FALSE

. Ex:

$a = array('a' => NULL, 'b' => 2);

$test = isset($a['a']); // $test will be assigned FALSE

In this case, using array_key_exists() function. Ex:

$a = array('a' => NULL, 'b' => 2);

$test = array_key_exists('a', $a); // $test will be TRUE

5.2.5. Deleting an element: using

unset()

function. Ex:

$a = array('a', 'b', 'c'); unset($a[1]); print_r($a); // Outputs: Array ( [0] => a [2] => c )

5.3.

Iteration (Looping):

5.3.1. Array Pointer: using

key(), current(), next(), prev(), reset(), end()

function. Ex:

$a = array('a', 'b', 'c'); while(key($a) !== null) {

echo key($a) . ': ' . current($a) . PHP_EOL; // Move pointer to next element

next($a); } // Outputs: 0: a 1: b 2: c

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

71

5.3.2. Using for() and foreach() function:

- Ex 1:

$a = array(3, 5, 7); $iCount = count($a);

for($i = 0; $i < $iCount; $i++) {

echo $a[$i] . '.'; }

// Displays "3, 5, 7, "

- Ex 2:

$a = array('blue' => 'small', 'green' => 'large'); foreach($a as $key => $value)

{

echo $key. ' : ' . $value . ','; }

//Displays

"blue : small, green : large, "

5.4.

Sorting:

Function name Sorts by Maintains key association

Order of sort Related functions sort()

Value

No

Low to high

rsort()

rsort()

Value

No

High to low

sort()

asort()

Value

Yes

Low to high

arsort()

arsort()

Value

Yes

High to low

asort()

natsort()

Value

Yes

Natural

natcasesort()

natcasesort()

Value

Yes

Natural, case

insensitive

natsort()

ksort()

Key

Yes

Low to high

asort()

krsort()

Key

Yes

High to low

ksort()

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

72

usort()

Value

No

User defined

uasort()

uasort()

Value

Yes

User defined

uksort()

uksort()

Key

Yes

User defined

uasort()

shuffle()

Value

No

Random

array_rand()

array_multisort()

Value

Associative

yes, numeric

no

First array or

sort options

array_walk()

Example of using

sort()

function:

$fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple'); sort($fruits);

foreach ($fruits as $key => $val) {

echo "fruits[" . $key . "] = " . $val . "\n"; } // Outputs: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange

Example of using

asort():

$fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple'); asort($fruits);

foreach ($fruits as $key => $val) {

echo "fruits[" . $key . "] = " . $val . "\n"; } // Outputs: fruits[b] = apple fruits[d] = banana fruits[a] = lemon fruits[c] = orange

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

73

Example of using

ksort()

:

$fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple'); ksort($fruits);

foreach ($fruits as $key => $val) {

echo "fruits[" . $key . "] = " . $val . "\n"; } // Outputs: fruits[a] = lemon fruits[b] = apple fruits[c] = orange fruits[d] = banana

5.5.

More Functions:

5.5.1. list() : assign variables as if they were an array.

5.5.2.

array

_

merge()

: merge one or more arrays.

5.5.3.

array_slice()

: extract a slice of the array.

5.5.4.

array_diff_*()

group: computes the difference of arrays

5.5.5.

array_intersect_*()

group: computes the intersection of arrays.

5.5.6.

array_push(), array_pop(), array_shift(), array_unshift()

: insert/

remove an element from array using queue and stack operation.

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

74

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

75

Chapter Exercise:

A>Can we use arithmetic operator (+, -, *, /) between 2 arrays. If yes, what is the result?

B>Simulate the game "ðánh bài Tiến lên" of Vietnamese, there are 4 people in game, each

has 13 cards. Using functions from beginning to this chapter to write the action of shuffle

cards and give each one 13 random cards.

***** difficult : write the function to find the number of "3 ñôi thông" in 13 cards of each

person.

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

76

Chapter 6

In document Athena Giao Trinh Php Mysql (Page 60-76)

Related documents