php functions & arrays
DESCRIPTION
Information on the utilization of functions and arrays.TRANSCRIPT
Functions & ArraysHenry Osborne
Basic Syntax
function name() { }
function hello() {
echo “Hello World!”;
}
hello();
Returning Values
function hello() {
return “Hello World!”;
}
$txt = hello();
echo hello();
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?”
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’;}
Variable Scope
• Three variable scopes exist:• Global
• Function
• Class
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
Variable Scope, cont’d
$a = “Hello”;
$b = “World”;
function hello() {
global $a, $b;
echo “$a $b”;
}
hello (); //Displays Hello World
Variable Scope, cont’d
$a = “Hello”;
$b = “World”;
function hello() {
echo $GLOBALS[‘a’].’ ‘.$GLOBALS[‘b’];
}
hello (); //Displays Hello World
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);
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”);
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
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();
Array Basics
$x[] = 10;
$x[’aa’] = 11;
echo $x[0]; // Outputs 10
Printing Arrays
• PHP provides two functions that can be used to output a variable’s value recursively• print_r()
• var_dump().
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.
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
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
Multi-dimensional Arrays
$array = array();
$array[] = array(’foo’, ’bar’);
$array[] = array(’baz’, ’bat’);
echo $array[0][1] . $array[1][0]; //output is barbaz
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";
}
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)
}
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)
}
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
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
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
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
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
Counting, Searching and Deleting Elements, cont’d
$a = array (’a’ => NULL, ’b’ => 2);
unset ($a[’b’]);
echo in_array ($a, 2); // False
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"
}
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);
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);
}
}
Array Iteration: foreach
$array = array(’foo’, ’bar’, ’baz’);
foreach ($array as $key => $value) {
echo "$key: $value";
}
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"
}
}
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"
}
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“
}
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.
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"
}
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)
}
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";
}
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)
}
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);
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"
}
Set Functionality
$a = array (1, 2, 3);
$b = array (1, 3, 4);
var_dump (array_diff ($a, $b));
var_dump (array_intersect ($a, $b));
Functions & Arrays