php functions & arrays

46
Functions & Arrays Henry Osborne

Upload: henry-osborne

Post on 18-Jan-2015

872 views

Category:

Education


2 download

DESCRIPTION

Information on the utilization of functions and arrays.

TRANSCRIPT

Page 1: PHP Functions & Arrays

Functions & ArraysHenry Osborne

Page 2: PHP Functions & Arrays
Page 3: PHP Functions & Arrays

Basic Syntax

function name() { }

function hello() {

echo “Hello World!”;

}

hello();

Page 4: PHP Functions & Arrays

Returning Values

function hello() {

return “Hello World!”;

}

$txt = hello();

echo hello();

Page 5: PHP Functions & Arrays

Returning Values

function hello() {

echo “Hello $who”;

if ($who == “World”) {

return;

}

echo “, how are you?”;

}

hello (“World”); //Displays “Hello World”

hello (“Reader”); //Displays “Hello Reader, how are you?”

Page 6: PHP Functions & Arrays

Returning Values

function &query($sql){ $result = mysql_query($sql); return $result;}

//The following is incorrect and will cause PHP to emit a notice when called.

function &getHello(){ return “Hello World”;}

//This will also cause the warning to be issued when called

function &test(){ echo ‘This is a test’;}

Page 7: PHP Functions & Arrays

Variable Scope

• Three variable scopes exist:• Global

• Function

• Class

Page 8: PHP Functions & Arrays

Variable Scope, cont’d

$a = “Hello World”;

function hello() {

$a = “Hello Reader”;

$b = “How are you?”;

}

hello ();

echo $a; //Will output Hello World

echo $b; //Will emit a warning

Page 9: PHP Functions & Arrays

Variable Scope, cont’d

$a = “Hello”;

$b = “World”;

function hello() {

global $a, $b;

echo “$a $b”;

}

hello (); //Displays Hello World

Page 10: PHP Functions & Arrays

Variable Scope, cont’d

$a = “Hello”;

$b = “World”;

function hello() {

echo $GLOBALS[‘a’].’ ‘.$GLOBALS[‘b’];

}

hello (); //Displays Hello World

Page 11: PHP Functions & Arrays

Variable-Length Argument Lists

function hello() {

if (func_num_args() > 0) {

$arg = func_get_arg(0);

echo “Hello $arg”;

} else {

echo ”Hello World”;

}

}

hello(“Reader);

Page 12: PHP Functions & Arrays

Variable-Length Argument Lists

function countAll($arg1){ if (func_num_args() == 0) { die(“You need to specify at least one argument”); } else { $args = func_get_args();

array_shift($args);

$count = strlen($arg1);

foreach ($args as $arg) { $count += strlen($arg); }

} return $count;}

echo countAll(“apple”,”pear”, “plum”);

Page 13: PHP Functions & Arrays

Passing Arguments by Reference

function countAll(&$count){ if (func_num_args() == 0) { die(“You need to specify at least one argument”); } else { $args = func_get_args();

array_shift($args);

$count = strlen($arg1);

foreach ($args as $arg) { $count += strlen($arg); }

}}

$count = 0;

countAll($count, “apple”,”pear”, “plum”);//count now equals 13

Page 14: PHP Functions & Arrays

Arrays

Page 15: PHP Functions & Arrays

Array Basics

$a = array (10, 20, 30);

$a = array (’a’ => 10, ’b’ => 20, ’cee’ => 30);

$a = array (5 => 1, 3 => 2, 1 => 3,);

$a = array();

Page 16: PHP Functions & Arrays

Array Basics

$x[] = 10;

$x[’aa’] = 11;

echo $x[0]; // Outputs 10

Page 17: PHP Functions & Arrays

Printing Arrays

• PHP provides two functions that can be used to output a variable’s value recursively• print_r()

• var_dump().

Page 18: PHP Functions & Arrays

Enumerative vs Associative

• Arrays can be roughly divided in two categories: enumerative and associative.

• Enumerative arrays are indexed using only numerical indexes

• Associative arrays(sometimes referred to as dictionaries) allow the association of an arbitrary key to every element.

Page 19: PHP Functions & Arrays

Enumerative vs Associative, cont’d

When an element is added to an array without specifying a key, PHP automatically assigns a numeric one that is equal to the greatest numeric key already in existence in the array, plus one:

$a = array (2 => 5);

$a[] = ’a’; // This will have a key of 3

$a = array (’4’ => 5, ’a’ => ’b’);

$a[] = 44; // This will have a key of 5

Page 20: PHP Functions & Arrays

Array keys are case-sensitive, but type insensitive. Thus, the key ’A’ is different from the key ’a’, but the keys ’1’ and 1 are the same. However, the conversion is only applied if a string key contains the traditional decimal representation of a number; thus, for example, the key ’01’ is not the same as the key 1.

NOTE WELL

Page 21: PHP Functions & Arrays

Multi-dimensional Arrays

$array = array();

$array[] = array(’foo’, ’bar’);

$array[] = array(’baz’, ’bat’);

echo $array[0][1] . $array[1][0]; //output is barbaz

Page 22: PHP Functions & Arrays

Unravelling Arrays

$sql = "SELECT user_first, user_last, lst_log FROM users";

$result = mysql_query($sql);

while (list($first, $last, $last_login) = mysql_fetch_row($result)) {

echo "$last, $first - Last Login: $last_login";

}

Page 23: PHP Functions & Arrays

Array Operations

$a = array (1, 2, 3);

$b = array (’a’ => 1, ’b’ => 2, ’c’ => 3);

var_dump ($a + $b);

array(6) {[0]=>

int(1)

[1]=>

int(2)

[2]=>

int(3)

["a"]=>

int(1)

["b"]=>

int(2)

["c"]=>

int(3)

}

Page 24: PHP Functions & Arrays

Array Operations, cont’d

$a = array (1, 2, 3);

$b = array (’a’ => 1, 2, 3);

var_dump ($a + $b);

array(4) {[0]=>

int(1)

[1]=>

int(2)

[2]=>

int(3)

["a"]=>

int(1)

}

Page 25: PHP Functions & Arrays

Comparing Arrays

$a = array (1, 2, 3);

$b = array (1 => 2, 2 => 3, 0 => 1);

$c = array (’a’ => 1, ’b’ => 2, ’c’ => 3);

var_dump ($a == $b); // True

var_dump ($a === $b); // False

var_dump ($a == $c); // False

var_dump ($a === $c); // False

Page 26: PHP Functions & Arrays

Comparing Arrays, cont’d

$a = array (1, 2, 3);

$b = array (1 => 2, 2 => 3, 0 => 1);

var_dump ($a != $b); // False

var_dump ($a !== $b); // True

Page 27: PHP Functions & Arrays

Counting, Searching and Deleting Elements

$a = array (1, 2, 4);

$b = array();

$c = 10;

echo count ($a); // Outputs 3

echo count ($b); // Outputs 0

echo count ($c); // Outputs 1

Page 28: PHP Functions & Arrays

Counting, Searching and Deleting Elements, cont’d

$a = array (’a’ => 1, ’b’ => 2);

echo isset ($a[’a’]); // True

echo isset ($a[’c’]); // False

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

echo isset ($a[’a’]); // False

Page 29: PHP Functions & Arrays

Counting, Searching and Deleting Elements, cont’d

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

echo array_key_exists (’a’, $a); // True

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

echo in_array (2, $a); // True

Page 30: PHP Functions & Arrays

Counting, Searching and Deleting Elements, cont’d

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

unset ($a[’b’]);

echo in_array ($a, 2); // False

Page 31: PHP Functions & Arrays

Flipping and Reversing

$a = array (’a’, ’b’, ’c’);

var_dump (array_flip ($a));

$a = array (’x’ => ’a’, 10 => ’b’, ’c’);

var_dump (array_reverse ($a));

array(3) {["a"]=>

int(0)

["b"]=>

int(1)

["c"]=>

int(2)

}

array(3) {[0]=>

string(1) "c"

[1]=>

string(1) "b"

["x"]=>

string(1) "a"

}

Page 32: PHP Functions & Arrays

Array Iteration

• One of the most common operations you will perform with arrays

• PHP arrays require a set of functionality that matches their flexibility

• “normal” looping structures cannot cope with the fact that array keys do not need to be continuous

$a = array (’a’ => 10, 10 => 20, ’c’ => 30);

Page 33: PHP Functions & Arrays

Array Iteration: Array Pointer

$array = array(’foo’ => ’bar’, ’baz’, ’bat’ => 2);

function displayArray(&$array) {

reset($array);

while (key($array) !== null) {

echo key($array) .": " .current($array) . PHP_EOL;

next($array);

}

}

Page 34: PHP Functions & Arrays

Array Iteration: foreach

$array = array(’foo’, ’bar’, ’baz’);

foreach ($array as $key => $value) {

echo "$key: $value";

}

Page 35: PHP Functions & Arrays

Passive Iteration

function setCase(&$value, &$key)

{

$value = strtoupper($value);

}

$type = array(’internal’, ’custom’);

$output_formats[] = array(’rss’, ’html’, ’xml’);

$output_formats[] = array(’csv’, ’json’);

$map = array_combine($type, $output_formats);

array_walk_recursive($map, ’setCase’);

var_dump($map);

array(2) {["internal"]=>

&array(3) {

[0]=>

string(3) "RSS"

[1]=>

string(4) "HTML"

[2]=>

string(3) "XML"

}

["custom"]=>

&array(2) {

[0]=>

string(3) "CSV"

[1]=>

string(4) "JSON"

}

}

Page 36: PHP Functions & Arrays

Sorting Arrays: sort()

$array = array(’a’ => ’foo’, ’b’ => ’bar’, ’c’ => ’baz’);

sort($array);

var_dump($array);array(3) {

[0]=>

string(3) "bar"

[1]=>

string(3) "baz"

[2]=>

string(3) "foo"

}

Page 37: PHP Functions & Arrays

Sorting Arrays: asort()

$array = array(’a’ => ’foo’, ’b’ => ’bar’, ’c’ => ’baz’);

asort($array);

var_dump($array);array(3) {

["b"]=>

string(3) "bar"

["c"]=>

string(3) "baz"

["a"]=>

string(3) "foo“

}

Page 38: PHP Functions & Arrays

Sorting Arrays

SORT_REGULAR Compare items as they appear in the array, without performing any kind of conversion. This is the default behaviour.

SORT_NUMERIC Convert each element to a numeric value for sorting purposes.

SORT_STRING Compare all elements as strings.

Page 39: PHP Functions & Arrays

Sorting Arrays: natsort()

$array = array(’10t’, ’2t’, ’3t’);

natsort($array);

var_dump($array);array(3) {

[1]=>

string(2) "2t"

[2]=>

string(2) "3t"

[0]=>

string(3) "10t"

}

Page 40: PHP Functions & Arrays

Anti-Sorting: shuffle()

$cards = array (1, 2, 3, 4);

shuffle($cards);

var_dump($cards);

array(4) {[0]=>

int(4)

[1]=>

int(1)

[2]=>

int(2)

[3]=>

int(3)

}

Page 41: PHP Functions & Arrays

Anti-Sorting: array_keys()

$cards = array (’a’ => 10, ’b’ => 12, ’c’ => 13);

$keys = array_keys ($cards);

shuffle($keys);

foreach ($keys as $v) {

echo $v . " - " . $cards[$v] . "\n";

}

Page 42: PHP Functions & Arrays

Anti-Sorting: array_rand()

$cards = array (’a’ => 10, ’b’ => 12, ’c’ => 13);

$keys = array_rand ($cards, 2);

var_dump($keys);

var_dump($cards);

array(2) {[0]=>

string(1) "a"

[1]=>

string(1) "b"

}

array(3) {["a"]=>

int(10)

["b"]=>

int(12)

["c"]=>

int(13)

}

Page 43: PHP Functions & Arrays

Arrays as Stacks, Queues and Sets

$stack = array();

array_push($stack, ’bar’, ’baz’);

var_dump($stack);

$last_in = array_pop($stack);

var_dump($last_in, $stack);

Page 44: PHP Functions & Arrays

Arrays as Stacks, Queues and Sets

$queue = array(’qux’, ’bar’, ’baz’);

$first_element = array_shift($queue);

var_dump($queue);

array_unshift($queue, ’foo’);

var_dump($queue);

array(2) {

[0]=>

string(3) "bar"

[1]=>

string(3) "baz"

}

array(3) {

[0]=>

string(3) "foo"

[1]=>

string(3) "bar"

[2]=>

string(3) "baz"

}

Page 45: PHP Functions & Arrays

Set Functionality

$a = array (1, 2, 3);

$b = array (1, 3, 4);

var_dump (array_diff ($a, $b));

var_dump (array_intersect ($a, $b));

Page 46: PHP Functions & Arrays

Functions & Arrays