Title: PHP Arrays
1PHP Arrays User-Defined Functions
2What are Arrays?
- An array in PHP is actually an ordered map. A
map is a type that maps values to keys. This type
is optimized in several ways, so you can use it
as a real array, or a list (vector), hashtable
(which is an implementation of a map),
dictionary, collection, stack, queue and probably
more. Because you can have another PHP array as a
value, you can also quite easily simulate trees.
3Array Types
- There are differing opinions on whether PHP
'really' supports different array types. The book
says 'yes', defining them as Indexed and
Associative Arrays, based on whether the key is
numeric or string. - PHP.net says "There are no different indexed and
associative array types in PHP there is only one
array type, which can both contain integer and
string indices. - It's common to refer to them like the book.
4So What's a Key?
- An array key can be thought of as the address or
reference to a specific value contained within an
array. - A key can be an integer or a string
- Floats used as keys are truncated to integers
- If you don't specify a key, the array key will
automatically start with 0 (zero) and auto
increment by 1 each time a new value is entered
into the array. - Key must be unique.
5Creating an Array
- An array can be created by the array()
language-construct. It takes a number of
comma-separated key value pairs. - colors array('red''rojo',
- 'green''verde',
- 'blue''azul')
value
key
6Accessing Array Values
- Array values can be accessed a number of ways.
Most directly, arrays can be output using print()
and echo. However, you have to indicate the key
of the value you wish to print, otherwise the
output will just be "Array". - Examples follow
7Example 1
- Create an array with numeric keys, automatically
created starting at zero - colors array('red',
- 'green',
- 'blue')
- echo colors1 //green
- echo colors //Array
- echo colors0 //red
8Example 2
- Create an array with numeric with keys starting
at 1, then incremented automatically by 1 - colors array(1'red',
- 'green',
- 'blue')
- echo colors1 //red
- echo colors3 //blue
- echo colors0 //Notice Undefined
9Example 3
- Create an array with string keys
- colors array('red''rojo',
- 'green''verde',
- 'blue''azul')
- echo colors'blue' //azul
- echo colors'red' //rojo
- echo colors0 //Notice Undefined
10Quickly View Array Structure
- You can quickly view the keys and values of an
array using print_r() - colors array('red',
- 'green',
- 'blue')
- print ""
- print_r(colors)
- print ""
Array ( 0 red 1 green 2
blue )
11Even More Detail
- You can quickly view the structure, keys and
values of an array using var_dump() - colors array('red',
- 'green',
- 'blue')
- print ""
- var_dump(colors)
- print ""
array(3) 0 string(3) "red" 1
string(5) "green" 2 string(4) "blue"
12Add Items to an Array
- After an array has been created, you can add
values to the 'end' of the array - colors 'orange'
- print ""
- print_r(colors)
- print ""
Array ( 0 red 1 green 2
blue 3 orange )
13Be Careful!
- Using the wrong syntax when adding values to your
array can overwrite your array - colors "turquoise" will overwrite the entire
array with the value of "turquoise". - Proper syntax for adding a value to an array is
- colors "turquoise" or
- colors5 "turquoise"
14Delete Array Element
- After an array has been created, you can add
values to the 'end' of the array - unset(colors2)
- print ""
- print_r(colors)
- print ""
Array ( 0 red 1 green 3
orange )
15Merge Arrays
- Combine arrays
- colors array('red',
- 'green',
- 'blue')
-
- others array('purple',
- 'pink')
- all array_merge(colors,others)
Array ( 0 red 1 green 2
blue 3 purple 4 pink )
16Count
- You can count the number of values in an array
- numColors count (colors)
17Delete or Reset Array
- Delete an array
- unset(colors)
- Reset an array (delete all keys and values but
keep array) - colors array()
18foreach Loops
- foreach loops are great way to access the values
in an array. - colors array('red',
- 'green',
- 'blue')
- foreach(colors as keyval)
- echo "Key key is val"
19Transform Arrays to Strings
- Let's take our colors and transform them into a
string with
at the end of each color - newString implode('
',colors)
20Transform Strings to Arrays
- Let's take our colors and transform them into a
string with
at the end of each color - names "Bob, Terry, Carl"
- guysArray explode(', ', names)
- print ""
- print_r(guysArray)
- print ""
Array ( 0 Bob 1 Terry 2
Carl )
21Sorting Arrays
- Arrays can be sorted by key or value
- You can sort and keep keys aligned, or sort
values and have new keys assigned.
22sort() Function
- sort() is alphabetical if values are strings, or
numeric if values are numeric. - colors array('red',
- 'green',
- 'blue')
- sort(colors)
- print_r(colors)
Array ( 0 blue 1 green 2
red )
23rsort() Function
- rsort() sorts in reverse
- colors array('green',
- 'red',
- 'blue')
- rsort(colors)
- print_r(colors)
Array ( 0 red 1 green 2
blue )
24ksort() Function
- ksort() sorts keys, keeping values correlated to
keys - colors array('green',
- 'red',
- 'blue')
- ksort(colors)
- print_r(colors)
Array ( 0 green 1 red 2
blue )
25shuffle() Function
- shuffle() randomly reorganizes the order of the
array and regens the keys - colors array('green',
- 'red',
- 'blue')
- shuffle(colors)
- print_r(colors)
Array ( 0 blue 1 red 2
green )
26extract() Function
- Use extract() to automatically create variables
from an array, where the variables created are
the keys and their values are the associated
array values - volume array ('can''16 oz',
- 'bottle''12 oz',
- 'gulp''32 oz')
- extract(volume)
- echo can // 16 oz
- echo bottle // 12 oz
- echo gulp // 32 oz
27array_search() Function
- array_search() searches the array for a given
value and returns the corresponding key if
successful. - array array(0 'blue', 1 'red', 2
'green', 3 'red') - key array_search('green', array)
- // key 2
- key array_search('red', array)
- // key 1
- Also see array functions
- array_key_exists(key, array) return (T, F)
- In_array(element, array) return (T, F)
28Multidimensional Arrays
- Arrays can contain other arrays.
- fruits array('apples',
- 'bananas',
- 'oranges')
- meats array('steaks',
- 'hamburgers',
- 'hotdogs')
- groceries array('Fruit'fruits,
- 'Meat'meats)
29Multidimensional Arrays
- Array
- (
- Fruit Array
- (
- 0 apples
- 1 bananas
- 2 oranges
- )
- Meat Array
- (
- 0 steaks
- 1 hamburgers
- 2 hotdogs
- )
- )
groceries'Meat''2' // hotdogs
30PHP functions
31PHP functions
- standard functions
- arrays, date and time, files and directories,
http, maths, strings, etc... - programmer-defined functions
- untyped parameters
- may or may not return a value or a reference
- unusual effect on variable scope
- can set default parameters
- can set variable parameters
32defining functions
result string1.string2 return
result s1 Gandalf s2 the
Grey echo strconcat (s1, s2) ?
33variable scope in functions
function weirdScope () a 2 // a is
local a 3 weirdScope () echo a //prints
3
function weirdScope () global a a 2
a 3 weirdScope () echo a // prints 5
34Example
- colors array('red','blue','green')
- places array('New York','Denver','Chicago')
- function makePulldown(fieldName, data)
- echo "\n"
- foreach(data as key value)
- echo "
- value
- \n"
-
- echo "\n"
- // end function
- makePulldown('favColors',colors)
- makePulldown('favPlaces',places)
35default parameters
- specify default parameters in the function
declaration - default value can be a constant, but not a
complex expression - any number of default parameters can be defined
- parameters with default values must be listed
after parameters without default values in the
function definition
36default parameters
function order (flavour vanilla, n 1)
switch (flavour) case vanilla
price n priceOf vanilla break
default echo Sorry, out of stock.
37Returning Values
- Previous function examples simply output to the
browser. A function can also return a value,
which can then be further processed. - function calcTax(amount, rate .074)
- return amount rate
- // end function
- amt 125.00
- tax calcTax(amt, .093)
- tax number_format(tax,2)
- total amt tax
- echo "Sub Total amt
- Tax tax
- Total total
"
38variable parameters
- if no parameters are declared for a function, you
can still pass multiple parameters - access to undeclared parameters is available
through special PHP functions - func_get_args ()
- func_num_args ()
- func_get_arg (argName)
39variable parameters
function countList () if (func_num_args ()
0) return false else for
(i 0 i count func_get_arg (i)