 |
CS 85 PHP Programming
|
Arrays
Reference: Programming PHP by Rasmus Lerdorf
Examples:
Chapter 5 Arrays
- array - a collection of data values, organized as an
ordered collection of key-value pairs
- very common and useful
- examples:
- a set of email addresses
- items from a select element that permits multiple selections
Indexed Versus Associative Arrays
- two kinds of arrays in PHP
- indexed
- keys are integers; 0-based
- associative
- keys are strings
- like two-column table: first column is key, second column is
value
- internally, all arrays are associative
- keys are unique
- arrays have an internal order
- there are functions to traverse array in this order
- order is normally that in which values were inserted
- can change order with sorting functions
Identifying Elements of an Array
- access values with arrayName[key]
- key aka
index
- e.g., $names[0], $names['0'],
$age['Jack']
- if the index is a constant, its value is used
- don't quote the key of an interpolated array lookup; e.g., "Hello, $person[name]";
Storing Data in Arrays
- storing a value in an array will create the array if necessary
- can initialize an array with the array() construct
- builds array from args
- array(val1, ...)
- array(key1 => val1, ...)
- array() // builds an empty array
Adding Values to the End of an Array
- use [] syntax
- e.g., $family[] = 'Pawel';
Assigning a Range of Values
- range(lb, ub)
- creates an array of consecutive integers or character values
- e.g., range(1, 100)
- e.g., range('a', 'z')
- e.g., range('able', 'zooey') same as range('a', 'z')
Getting the Size of an Array
- count(arrayName)
- alias sizeof(arrayName)
- return number of elements in the array
Padding an Array
- to create an array initialized to the same value
- newArray = array_pad(existingArray,
minimumElements, value)
- use negative value for minimumElements to
add to the start of the array
Multidimensional Arrays
- array values can be arrays
- refer to elements with more []s
- to interpolate an array lookup in a multidimensional array, enclose in {}; e.g., "the
name is {$name[0][1]}."
Extracting Multiple Values
- to copy all array values into variables
- list(varList) = arrayName;
- construct (not a function)
- copied in internal order
- extra values in arrayName are
ignored
- extra values in varList are set to NULL
Slicing an Array
- array arr2 = array_slice(array arr1,
int offset, int length);
- arr2 will have numeric keys
starting at 0
- combine with list() to extract only
some values to variables
Splitting an Array into Chunks
- divides array into smaller, evenly sized arrays
- array chunks array_chunk(array arr,
int size, [, bool preserve_keys])
Keys and Values
- array keys array_keys(array arr)
- returns keys in internal order
Checking Whether an Element Exists
- array_key_exists(key, array)
- similar to isset(), but not quite the
same
Removing and Inserting Elements in an Array
- array_splice(array arr, int start,
[, int length [, array replacement]]
Converting Between Arrays and Variables
Creating Variables from an Array
- extract(array arr [, int extract_type]
[, string prefix])
- the keys become the variable names
- if the variable name already exists, it is overwritten
Creating an Array from Variables
- array arr compact('var1', 'var2',
...)
- array arr compact(array arr)
- creates an associative array with keys 'var1',
'var2', ...
Traversing Arrays
- typically we need to process each element of an array
The foreach Construct
- most common way to loop over an array's elements
- see ch. 2
- operates on a copy of the array
The Iterator Functions
- iterator - the pointer to the current element (of the
array)
- current() - returns the current element
- reset() - moves iterator to first
element; returns the element
- next() - moves iterator to next element;
returns the element
- prev() - moves iterator to previous
element; returns the element
- end() - moves iterator to last element;
returns the element
- each() - returns the key and value of the
current element (as an array); moves iterator to next element
- key() - returns the key of the current
element
- Example 5-1web.php Building a table
with the iterator functions
Using a for Loop
- for indexed arrays
- operates on the array itself
- processes elements in key order (regardless of internal order)
Calling a Function for Each Array Element
- array_walk(array arr, string function_name,
arg)
- function_name has two or three
parameters - element value, key, thirdArgumentToArray_walk
- processes elements in their interal order
Reducing an Array
- mixed result array_reduce(array arr,
string function_name [, default])
- applies a function to each element
- builds a single value
Searching for Values
- bool found in_array(mixed to_find,
array arr [, bool strict])
- strict == true requires type
to match
- Example 5-2-b.php Searching an
array
- mixed key array_search(mixed to_find,
array arr [, bool strict])
- returns key of found element
Sorting
- changes the internal order of the elements
Sorting One Array at a Time
- nine sort functions
- sort() - standard
- rsort() - reverse
- usort() - user
- asort() - associative
- arsort() - associative reverse
- uasort() - user associative
- ksort() - key
- krsort() - key reverse
- uksort() - user key
- Example 5-3-b.php Sorting arrays
Natural-Order Sorting
- natsort() - natural
- natcasesort() - natural lowercase
Sorting Multiple Arrays at Once
- array_multisort(array arr1 [, int sort_order]
[, array arr2 [, int sort_order] ...)
- similar to a join operation on a database
Reversing Arrays
- array arr2 = array_reverse(array arr1)
- reverses the internal order of the elements
- array arr2 array_flip(array arr1)
- switches keys with values
Randomizing Order
- shuffle(array arr)
- puts elements in random order
Acting on Entire Arrays
Calculating the Sum of an Array
- mixed sum array_sum(array arr)
Merging Two Arrays
- array result array_merge(array arr1,
array arr2, ...)
Calculating the Difference Between Two Arrays
- see later section on sets
Filtering Elements from an Array
- array result array_filter(array arr1,
string function_name)
- result is an array containing the
elements of arr1 for which function_name returns true
Using Arrays
- arrays appear in almost all PHP programs
- can use arrays to implement sets, stacks, and queues
Sets
- basic operations: union, intersection, difference
- can use arrays, but must remove duplicates
- union
- all elements from both sets
- array_unique(array_merge(array1, array2,
...));
- intersection
- elements common to all sets
- array_intersect(array1, array2,
...)
- difference
- elements in array1 that are
not in array2
- array_diff(array1, array2)
Stacks
- LIFO data structure
- array_push($array, value)
- same as assignment to $array[]
- array_pop($array)
- removes last element from $array
- returns the element
- useful for maintaining state
- Example 5-4web.php State debugger
Queues
- array_shift()
- array_unshift()
Last Modified: