PHP Arrays
PHP Arrays
Using Arrays
1
Arrays
Topics:
Numerically indexed arrays
Non-numerically indexed arrays (hashes, associative
arrays)
Array operators
Multidimensional arrays - read
Array sorting
Other array functions
Complete reference for arrays at
http://www.php.net/array
2
Arrays
An array = a set of data represented by a single variable name
Example, the $products array:
4
Creating Numerically Indexed Arrays
Create an indexed array by assigning a value to an element of
an array that doesn’t exist (the array!):
$array_name[index] = value; or $array_name[] = value;
Writing to an indexed array with empty [ ] creates the new element at
end of the array PHP arrays don’t have fixed length!
Example:
$list = array(2, 4, 6, 8);
$list[ ] = 10; $list is now array(2, 4, 6, 8, 10)
Example:
$Provinces[] = "Newfoundland and Labrador";
$Provinces[] = "Prince Edward Island";
if $Provinces didn’t exist before, it is created and has 2 elements,
indexed 0 and 1.
5
Creating Numerically Indexed Arrays
Other ways to create indexed arrays:
$new_array = $existing_array; // as a single unit
The range(…) function creates an array with a range of values
Can be used with either numbers or characters (single letters)
$n = range(4, 7); is same as $n = array(4, 5, 6, 7);
8
Creating Arrays
http://cscdb.nku.edu/csc301/frank/PHP_Arrays/arrays_cre
ating.php
9
Accessing Array Contents
Read/modify an array element’s value as usual
Writing to array with a currently-undefined key (or beyond the
end of an indexed array) creates a new element.
Use the unset(…) function to eliminate:
An array:
$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);
unset($products); // $products doesn’t exist after this statement
An array element:
$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);
unset($products[0]);
// $products remains with 2 elements only, indexed 1 and 2
10
Sequential Access to Array Elements
Logical internal structure of arrays:
elements are stored in a linked list of cells;
each cell includes both the key and the value of the element;
cells are linked in the order they are created - numerically indexed arrays too
classic arrays are ordered by index, PHP arrays are ordered by creation order
array elements can be can accessed in creation order or key order if
keys are numbers
11
Sequential Access to Array Elements
Regular for loops for numerically indexed arrays:
12
Sequential Access to Array Elements
Foreach loops, specially designed for arrays, can be used
for all types of indexes.
For numerically indexed arrays, use:
foreach($arrayName as $val)
$val steps through each of the values in $arrayName
13
Sequential Access to Array Elements
Foreach loops, examples:
$prices = array('Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4);
foreach ($prices as $key => $val) {
echo "$key - $val, ";
}
14
Sequential Access to Array Elements
Important - to modify the array elements’ values in a foreach
loop, use the reference operator:
$prices = array('Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4);
foreach ($prices as $key => &$val) {
$val *= 1.05; // increases product prices by 5%
}
17
Size of an Array
Two functions get the number of elements of an array passed to
them; return 0 for an empty array and 1 for a scalar variable:
count($a )
sizeof($a)
array_count_values($array_name) returns an associative array with:
keys = the distinct values from $array_name
the value for each key is the number of times that key occurs in
$array_name
Example: $list = array(1, 2, 6, 6, 6, 2);
$c = count($list); // $c contains 6
$ac = array_count_values($list);// $ac contains 1=>1, 2=>2, 6=>3
18
Sorting Arrays
3 types of sort:
Indexed array – sort values and reset indexes
Hash – sort by values
Hash – sort by keys
19
Sorting Arrays
The ascending and descending sort routines are just called
with the array name
ascending/descending sort() also take an optional argument that
specifies the sort type: SORT_REGULAR (the default; alphabetically
for strings, numeric order for numbers), SORT_NUMERIC, or
SORT_STRING
They sort the original array
User-defined sort takes second argument
The name of a function that returns <0, 0 or >0 given 2 input
arguments based on their relative order (<0 means 1st is less than 2nd)
20
Arrays Sorting
http://cscdb.nku.edu/csc301/frank/PHP_Arrays/arrays_sor
ting.php
21
Loading Arrays from Files
Recall that file($file_name) returns the entire file content as an array:
each line in the file is one element of this array.
A line can be split into fields using
array explode(string $separator, string $line_string [, int $limit])
Ex: $s = "15:42, 20th April\t4 tires\t1 oil\t6 spark plugs\t$434.00\t22 4th St, Troy";
$a = explode (“\t”, $s);
// $s is exploded into: "15:42, 20th April", "4 tires", "1 oil", "6 spark plugs",
// "$434.00", and "22 4th St, Troy", which are stored in the array $a
The optional limit parameter can be used to limit the number of parts returned
Opposite for explode(): string implode(string $separator, array $arr)
it combines an array’s elements’ values into a single string, separated by the
specified separator
22